How to bind drop down list with string array in ASP.NET?

拟墨画扇 提交于 2021-01-27 10:33:12

问题


I am able to bind drop down list with a string array by doing so (not sure whether this is the correct way to implement):

string[] items = { "111", "222", "333" };
ddlSearch.DataSource = items;
ddlSearch.DataBind();

However, what I actually wanted is: When I click the drop down list, the first item showing in the list shall be 111 followed by 222 and 333.

How am I able to add the strings of text to show in the drop down list when I click the drop down list button?

Java has an easy way to add items to be displayed in the list, but how do we do it in C#? (I am very new to C# by the way.)


回答1:


It would be easier to use List<string>

Markup can be

<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

The backend code would look like

var items = new List<string> {
"111",
"222",
"333"
};
items.Sort(); 

DropDownList1.DataSource = items;
DropDownList1.DataBind();



回答2:


Source: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasource.contexttypename(v=vs.110).aspx

public class MovieLibrary
{
    string[] _availableGenres = { "Comedy", "Drama", "Romance" };

    public MovieLibrary()
    {
    }

    public string[] AvailableGenres
    {
        get
        {
            return _availableGenres;
        }
    }
}


<asp:LinqDataSource 
    ContextTypeName="MovieLibrary" 
    TableName="AvailableGenres" 
    ID="LinqDataSource1" 
    runat="server">
</asp:LinqDataSource>
<asp:DropDownList 
    DataSourceID="LinqDataSource1"
    runat="server" 
    ID="DropDownList1">
</asp:DropDownList>


来源:https://stackoverflow.com/questions/27968600/how-to-bind-drop-down-list-with-string-array-in-asp-net

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