Adding attributes to dropdownlist in asp.net
In this article we are going to see how to add attributes to dropdownlist in asp.net using c#. We will add some custom attributes to the dropdownlist in the page_load event of the page and use it whenever some selection gets changed in the dropdownlist to dislay it as a label text.
In this article we are going to see how to add attributes to dropdownlist in asp.net.
Step1: Add dropdownlist control and a label to your webpage as shown below.
<asp:DropDownList AutoPostBack="true" ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Please Select" Value="0"></asp:ListItem>
<asp:ListItem Text="Red" Value="Red"></asp:ListItem>
<asp:ListItem Text="Blue" Value="Blue"></asp:ListItem>
<asp:ListItem Text="Green" Value="Green"></asp:ListItem>
<asp:ListItem Text="White" Value="White"></asp:ListItem>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
This dropdownlist has some items added to it. Label1 is used to display custom attribute "index" value of the dropdownlist item selected.
Step2: In the code-behind file add below code which adds attribute "index" with some value to the dropdownlist.
protected void Page_Load(object sender, EventArgs e)
{
for(int i=0;i
DropDownList1.Items[i].Attributes.Add("index", i.ToString());
}
}
Step3:Whenever user selects some item in the dropdownlist, its associated attribute is displayed as label text as shown below:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedItem.Attributes["index"];
}