【问题标题】:How to bind drop down list with string array in ASP.NET?如何在 ASP.NET 中将下拉列表与字符串数组绑定?
【发布时间】:2015-01-15 16:48:14
【问题描述】:

我可以通过这样做将下拉列表与字符串数组绑定(不确定这是否是正确的实现方式):

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

然而,我真正想要的是:当我点击下拉列表时,列表中显示的第一项应该是111,然后是222333

当我单击下拉列表按钮时,如何添加要在下拉列表中显示的文本字符串?

Java 有一种简单的方法来添加要在列表中显示的项目,但我们如何在 C# 中做到这一点? (顺便说一下,我对 C# 很陌生。)

【问题讨论】:

  • 这样。项目在下拉菜单中的显示顺序是什么?
  • 您要重新排列您的清单吗?或者您是否希望在列表中添加其他字符串?如果要添加项目,使用List<string>Dictionary<string> 可能更容易
  • 我看过几个使用列表的例子,是否可以用字符串数组填充下拉列表?顺序无关紧要。例如,我只想要下拉列表中的“111”、“222”、“333”。
  • 那么问题来了,如何添加到数组中?
  • 问题是“如何用字符串填充下拉列表” - 最好是字符串数组

标签: c# asp.net drop-down-menu


【解决方案1】:

使用List<string>会更方便

标记可以是

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

后端代码如下所示

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

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

【讨论】:

    【解决方案2】:

    来源: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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多