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 populate the drop down with data from the DataSet.
Can you show me some sample markup and / or VB.Net coding that is required to populate the drop down list with the DataSet data?
<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:
<body>
<form id="form1" runat="server">
<div>
Fruits
<asp:DropDownList ID="DropDownListWithFruits" runat="server" DataTextField="FruitName" DataValueField="FruitId" />
</div>
</form>
</body>
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With