Designer View
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Select a colour : "></asp:Label>
</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</td>
</tr>
</table>
Add / bind data into dropdownlist
1. Manual binding
private void BindDropDownList()
{
DropDownList1.Items.Clear();
DropDownList1.Items.Insert(0, new ListItem("-SELECT-", "-1"));
DropDownList1.Items.Add(new ListItem("Red", "1"));
DropDownList1.Items.Add(new ListItem("Yellow", "2"));
DropDownList1.Items.Add(new ListItem("Green", "3"));
}
2. Using DataTable
private void BindDropDownList()
{
DataTable tableColour = GetTable();
DropDownList1.Items.Clear();
DropDownList1.Items.Insert(0, new ListItem("-SELECT-", "-1"));
DropDownList1.DataSource = tableColour; //bind the ddp_dataview to dataview
DropDownList1.DataTextField = "Colour";
DropDownList1.DataValueField = "Colour Code";
DropDownList1.DataBind();
}
private DataTable GetTable()
{
DataTable table = new DataTable();
table.Columns.Add("Colour Code", typeof(int));
table.Columns.Add("Colour", typeof(string));
table.Rows.Add(1, "Red");
table.Rows.Add(2, "Yellow");
table.Rows.Add(3, "Green");
return table;
}
Result:
No comments:
Post a Comment