Search code examples
asp.neteventslistboxweb-controls

Databinding listbox and set css class


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!


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");
            }
        }