asp.net dropdownlist attributes add
this example show you how to add custom attributes/styles to dropdownlist. here we create a dropdownlist
then apply different color for each items of dropdownlist. we find the dropdownlist each item then add a
attribute style here with it's color value. in this way you can apply many css style in dropdownlist items.
dropdownlist-attributes-add.aspx
<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
ListItem li = new ListItem(string.Empty,string.Empty);
ListItem li1 = new ListItem("Crimson", "1");
ListItem li2 = new ListItem("SkyBlue", "2");
ListItem li3 = new ListItem("SeaGreen", "3");
DropDownList1.Items.Add(li);
DropDownList1.Items.Add(li1);
DropDownList1.Items.Add(li2);
DropDownList1.Items.Add(li3);
}
DropDownList1.Items[1].Attributes.Add("style", "color:Crimson");
DropDownList1.Items[2].Attributes.Add("style", "color:SkyBlue");
DropDownList1.Items[3].Attributes.Add("style", "color:SeaGreen");
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "you selected....<br />";
Label1.Text += "item: " + DropDownList1.SelectedItem.Text;
Label1.Text += "<br />value: " + DropDownList1.SelectedItem.Value;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net dropdownlist attributes add</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
asp.net example - dropdownlist attributes add
</h2>
<hr width="550" align="left" color="Gainsboro" />
<asp:Label
ID="Label1"
runat="server"
Text="select an item from dropdownlist."
Font-Size="X-Large"
Width="350"
>
</asp:Label>
<br /><br />
<asp:DropDownList
ID="DropDownList1"
runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
Width="350"
Font-Size="X-Large"
>
</asp:DropDownList>
</div>
</form>
</body>
</html>
- How to add an onClick event to a Label
- How to trim text with ellipsis in a Label
- How to add margin to a Label
- How to add CSS class to DropDownList each items
- How to change DropDownList alternate item color
- How to change DropDownList selected item color
- How to sort ListBox items by value
- How to display different tooltip on ListBox items
- How to get CheckBoxList selected values using Linq
- How to set the maximum limit of selection in a CheckBoxList