Friday, 4 March 2016
How To Add optgroup Attribute to DropDownList in C# using JQuery,Asp.Net
C# Code:
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Number", typeof(int));
//
// Here we add five DataRows.
//
table.Rows.Add(1, 57);
table.Rows.Add(2, 23);
table.Rows.Add(3, 99);
table.Rows.Add(4, 8);
table.Rows.Add(5, 74);
DropDownList1.DataSource = table;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Number";
DropDownList1.DataBind();
}
}
Asp Code
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//Create groups for dropdown list
$("select#DropDownList1 option[classification='LessThanFifty']").wrapAll("<optgroup label='Less than fifty'>");
$("select#DropDownList1 option[classification='GreaterThanFifty']").wrapAll("<optgroup label='Greater than fifty'>");
});
</script>
<style>
optgroup
{
background-color:Gray ;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" Width="200px" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true"
OnDataBound="DropDownList1_DataBound">
</asp:DropDownList>
</form>
</body>
</html>
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
foreach (ListItem item in ((DropDownList)sender).Items)
{
if (System.Int32.Parse(item.Text) < 50)
item.Attributes.Add("classification", "LessThanFifty");
else
item.Attributes.Add("classification", "GreaterThanFifty");
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string val = DropDownList1.SelectedValue.ToString();
}
}
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment