Binding Dropdown list



Static from CS

  List<ListItem> li = new List<ListItem>();
                li.Add(new ListItem { Text = "Select", Value = "0" });
                li.Add(new ListItem { Text = "India", Value = "0" });
                li.Add(new ListItem { Text = "Pak", Value = "0" });
                li.Add(new ListItem { Text = "Ban", Value = "0" });
                li.Add(new ListItem { Text = "SL", Value = "0" });

                DropDownList1.DataSource = li;
                DropDownList1.DataBind();




Static from ASPX

<asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Text="Select" Value="0"></asp:ListItem>
        <asp:ListItem Text="India" Value="1"></asp:ListItem>
        <asp:ListItem Text="Pak" Value="2"></asp:ListItem>
        <asp:ListItem Text="Ban" Value="3"></asp:ListItem>
        <asp:ListItem Text="SL" Value="4"></asp:ListItem>
</asp:DropDownList>



Dynamic Binding

                         //dt is the DataTable obtained from SQL Server using ADO.NET
                DropDownList1.DataSource = dt;
                DropDownList1.DataTextField = "EmpName";
                DropDownList1.DataValueField = "ID";
                DropDownList1.DataBind();



Insert or ADD

DropDownList1.Items.Insert(0, new ListItem { Text = "Select", Value = "0" });
DropDownList1.Items.Insert(1, new ListItem { Text = "India", Value = "1" });
DropDownList1.Items.Insert(2, new ListItem { Text = "Pak", Value = "2" });
DropDownList1.Items.Insert(3, new ListItem { Text = "Ban", Value = "3" });
DropDownList1.Items.Insert(4, new ListItem { Text = "SL", Value = "4" });
DropDownList1.Items.Insert(5, "AFG");

DropDownList1.Items.Add("India");
DropDownList1.Items.Add(new ListItem { Text = "China", Value = "5" });


0 comments

Post a Comment