Populating An Asp.net Drop Down List With Dataset Data From Dataset Created With Dataset Designer
We have an ASP.Net / VB.Net web form containing a drop down list in the markup of the aspx file. There is also a DataSet created with the DataSet designer. We would like to populat
Solution 1:
<asp:DropDownListID="MyDropDownList"runat="server"DataTextField="SomeString"DataValueField="SomeUniqueId" />
Code-behind:
protectedvoidPage_Load(object sender, EventArgs e)
{
var myDataSet = new DataSet(); // replace with your dataset
MyDropDownList.DataSource = myDataSet;
MyDropDownList.DataBind();
}
VB.Net:
ProtectedSub Page_Load(sender AsObject, e As System.EventArgs) HandlesMe.Load
Dim aDataSet As DataSet
MyDropDownList.DataSource = aDataSet
MyDropDownList.DataBind()
EndSub
And you see the "DataTextField" and "DataValueField" in the markup? There's where you put the name of fields you want to use as id (data value) and to display (data text) in the drop-down list.
Here's an example:
Markup
<body><formid="form1"runat="server"><div>
Fruits
<asp:DropDownListID="DropDownListWithFruits"runat="server"DataTextField="FruitName"DataValueField="FruitId" /></div></form></body>
Code behind
protectedvoidPage_Load(object sender, EventArgs e)
{
var myDataSet = new DataSet();
var table1 = new DataTable();
table1.Columns.Add("FruitName");
table1.Columns.Add("FruitId");
table1.Rows.Add("Apple", 1);
table1.Rows.Add("Banana", 2);
table1.Rows.Add("Grapefruit", 3);
myDataSet.Tables.Add(table1);
DropDownListWithFruits.DataSource = myDataSet;
DropDownListWithFruits.DataBind();
}
Solution 2:
ComboboxName.DataSource =YourDataSetName
ComboboxName.DataValueField =Name OF the field that you want to return its selected value
for example "ID"
ComboboxName.DataTextField =Name OF the field that you want to view in the drop down list
for example "Name"
ComboboxName.DataBind()
Post a Comment for "Populating An Asp.net Drop Down List With Dataset Data From Dataset Created With Dataset Designer"