Question

I want to get the values from the database to generate a listbox which items are in different class. In HTML, I hope it will be like

<option value="a" class="A">A</option>

In asp.net, I wrote this but I don't know if there is any method that can help to specify the class attribute in the databinding stage. (At this stage, I can only put the text and the value of the option items correctly.)

lb.DataSource = CreateDataSourceForLB()
lb.DataTextField = "TextField"
lb.DataValueField = "ValueField"
lb.DataBind()

Many thanks for the help!

Was it helpful?

Solution

You need Add Databound event of list box and add class attribute to its each list items.

protected void ListBox1_DataBound(object sender, EventArgs e)
    {
        foreach (ListItem li in ListBox1.Items)
        {
            li.Attributes.Add("Class", "A");
        }
    }

OTHER TIPS

I don't think there is at the databind stage you would just have to loop all the items.

foreach (ListItem item in lb.Items)
{
              item.Attributes.Add("class", item.Value.ToUpper());      
}

I don't think you can bind the attributes of a DropdDownList to set HTML attributes, however, you could iterate through all the items after you binded the control, and set their attributes:

        foreach (var item in this.ddl.Items.OfType<ListItem>())
        {
            item.Attributes.Add("class", "koko");
        }

The above code generates the following HTML:

 <select name="ddl" id="ddl">
<option selected="selected" value="" class="koko">---Select---</option>
<option value="1" class="koko">New Hire - Job not specified</option>
<option value="2" class="koko">Chief Executive Officer</option>
    .....
 </select>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top