1

I'm building a checkbox list and altering it in code for the purposes of using jquery to filter the results to the client.

This code runs in the databound event:

    foreach (ListItem item in checkBoxList.Items)
    {
        foreach (object dataItem in sdsOutsideReports.Select(DataSourceSelectArguments.Empty))
        {
            if (Convert.ToInt16(DataBinder.GetPropertyValue(dataItem, "AttributeID")) == Convert.ToInt16(item.Value))
            {
                item.Attributes.Add("Requirement"
                    , DataBinder.GetPropertyValue(dataItem, "AttributeDataType").ToString()
                );
            }
        }
    }

The result, unfortunately, is a checkboxlist wrapped in a span. That span has an attribute of "requirement" which is filled out. Whatever, that seems to just be the way .net does it:

<span requirement="TypeRequirement">
<input id="ctl00_ContentPlaceHolder1_cblPrerequisites_11" type="checkbox" name="ctl00$ContentPlaceHolder1$cblPrerequisites$11">
<label for="ctl00_ContentPlaceHolder1_cblPrerequisites_11">Final Exam</label>
</span>

But when I try to access the attributes collection of the checkbox on postback to interact with certain items differently then others, I get no attributes!

This code fails with a nullreference:

    String Test;
    foreach (ListItem SelectedItem in checkBoxList.Items)
    {
        if (SelectedItem.Selected) {
            Test = SelectedItem.Attributes["requirement"].ToString();
        }
    }

I did a property inspection and there's no attributes related to this checkboxlist.

What are my options for fixing this weirdness?

C Bauer
  • 5,003
  • 4
  • 33
  • 62
  • 3
    I'm having the same problem. God I hate webforms. What f&*%ing joker decided it would be a good idea to stick a wrapping span tag AROUND the input field when adding a custom attribute? Anyway, you could possibly use jQuery/javascript to add the attribute & value `requirement="TypeRequirement"` to your checkboxes? If you use the actual `` field you can use `chkBox.InputAttributes.Add("requirement", "TypeRequirement");`. This won't add a wrapping span. See http://stackoverflow.com/a/12325384/654708. Unfortunately `InputAttributes`doesn't exist on `ListItem`. – GFoley83 Jun 26 '13 at 18:07
  • 2
    And FYI: the `ListItem` class is sealed as well. So you can't even override the `Render` function for the `ListItem` control to exclude the `span` tag when a custom attribute is present. – GFoley83 Jun 26 '13 at 18:14

0 Answers0