【问题标题】:method in c# to populate drop down list [closed]c#中填充下拉列表的方法[关闭]
【发布时间】:2014-02-16 05:59:51
【问题描述】:

我需要在 c# 中创建一个代码隐藏方法,该方法将填充我的 ASP.NET 页面上的下拉列表。由于我对 c# 非常陌生,因此我无法解决这个问题。我希望有人能指出我正确的方向。到目前为止我所尝试的一切都没有奏效。我感谢并欢迎任何帮助或想法。

【问题讨论】:

  • 看看this
  • 请解释是什么让您认为再添加一个示例将帮助您使用此代码 - 在特定实现中没有按您预期的那样工作,您已经尝试过什么,...到目前为止,您的帖子包含你想做什么和很多“谢谢”/“新来的”/“搜索了很多”文本而不是你卡在哪里的信息。

标签: c# asp.net code-behind


【解决方案1】:

将 DropDownList 添加到 Asp.Net 页面并添加以下代码。

yourDropDownList.DataSource = yourDataSource;
yourDropDownList.DataTextField = "YourTextField";
yourDropDownList.DataValueField = "YourValueField";
yourDropDownList.DataBind();

DropDownList

【讨论】:

    【解决方案2】:

    有几种方法可以填充下拉列表 (System.Web.UI.WebControls.DropDownList)。下面给出了其中的几个:

    备选方案 1:

    假设你有一个字符串列表并且你想插入它们。你可以这样做:

    List<string> list = new List<string> { "A", "B"};
    DropDownList ddl = new DropDownList();
    ddl.DataSource = list;
    ddl.SelectedIndex = 0; // if u want to select the very 1st item by default
    

    备选方案 2:

    假设你有如下类:

    public class Test
    {
        public string Name { get; set;}
        public int Value { get; set;}
    }
    

    并且您想将Test 对象列表绑定到下拉列表。您还希望在 ddl 中显示 Name 属性,但希望在从 ddl 中选择特定项目时获取相应的 Value 属性。方法如下:

    List<Test> tests = new List<Test>
                           {
                               new Test
                                   {
                                       Name = "Test1",
                                       Value = 100
                                   },
                               new Test
                                   {
                                       Name = "Test2",
                                       Value = 80
                                   }
                           }
    
    DropDownList ddl = new DropDownList();
    ddl.DataSource = list;
    ddl.DataTextField = "Name"; // property u wanna display
    ddl.DataValueField = "Value"; // property u wanna retrieve value from
    ddl.DataBind();
    ddl.SelectedIndex = 0; // if u want to select the very 1st item by default
    

    现在由您来决定满足您的需求。祝你好运!

    【讨论】:

    • 我的代码中有这个 List list = new List { "Month", "1", "2", "3", "4", "5", “6”、“7”、“8”、“9”、“10”、“11”、“12”}; DropDownListMonth.DataSource = 列表; DropDownListMonth.DataBind(); DropDownListMonth.SelectedIndex = 0; foreach (DropDownListMonth.Items 中的 ListItem 项) { int i = 0;字符串月份 = Convert.ToString(i); DropDownListMonth.DataValueField = 月; i = Convert.ToInt32(月);我++; }
    • 当我尝试在页面上执行任何操作时出现错误:DataBinding: 'System.String' does not contain a property with name '0'.
    • 如果我取出 fpr 循环,当我尝试从列表中选择一个值时,它不会更改为该值
    • 我已将您的 cmets 放入您的问题中
    • DropDownListMonth.DataValueField 仅应在绑定对象的类具有您想用作值字段的任何属性时设置。在您的情况下,您不需要 DropDownListMonth.DataValueField ,因为您绑定了 List&lt;string&gt; 其中 string 类本身代表一个值。所以请在我的回答中参考ALTERNATIVE 1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多