Populating an ASP.Net Drop Down List with DataSet data from DataSet created with DataSet designer

大憨熊 提交于 2019-12-23 21:26:43

问题


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?


回答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();
}



回答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()



来源:https://stackoverflow.com/questions/13701013/populating-an-asp-net-drop-down-list-with-dataset-data-from-dataset-created-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!