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:DropDownList ID="MyDropDownList" runat="server" DataTextField="SomeString" DataValueField="SomeUniqueId" />
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
var myDataSet = new DataSet(); // replace with your dataset
MyDropDownList.DataSource = myDataSet;
MyDropDownList.DataBind();
}
VB.Net:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim aDataSet As DataSet
MyDropDownList.DataSource = aDataSet
MyDropDownList.DataBind()
End Sub
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>
<form id="form1" runat="server">
<div>
Fruits
<asp:DropDownList ID="DropDownListWithFruits" runat="server" DataTextField="FruitName" DataValueField="FruitId" />
</div>
</form>
</body>
Code behind
protected void Page_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"