【问题标题】:dropdown list item selection in asp.netasp.net中的下拉列表项选择
【发布时间】:2013-05-09 12:03:35
【问题描述】:

我正在使用以下代码将字典对象绑定到下拉列表中并从下拉列表中选择值。

 protected void Page_Load(object sender, EventArgs e)
    {
        Dictionary<int, string> dict = new Dictionary<int, string>();
        dict.Add(1, "apple");
        dict.Add(2, "bat");
        dict.Add(3, "cat");
        ddl.DataSource = dict;
        ddl.DataValueField = "Key";
        ddl.DataTextField = "Value";  //will display in ddl
        ddl.DataBind();
    }
    protected void btn_Click(object sender, EventArgs e)
    {
        string key = ddl.SelectedValue;
        string value = ddl.SelectedItem.Text;
    }

无论我在 ddl 中选择什么值,它的键值总是“1”,值总是“苹果”。我的代码有什么问题?

【问题讨论】:

    标签: c# asp.net dictionary html-select


    【解决方案1】:

    那是因为你绑定了每个post上的列表,你应该检查IsPostBacklike

    protected void Page_Load(object sender, EventArgs e)
    {
         if(!Page.IsPostBack) // better if you refactor binding code to a method
           {
            Dictionary<int, string> dict = new Dictionary<int, string>();
            dict.Add(1, "apple");
            dict.Add(2, "bat");
            dict.Add(3, "cat");
            ddl.DataSource = dict;
            ddl.DataValueField = "Key";
            ddl.DataTextField = "Value";  //will display in ddl
            ddl.DataBind();
           }
    }
    

    【讨论】:

      【解决方案2】:

      您的dropdownlist 每次页面加载时都会重置,因此请使用IsPostBack 更新您的代码,如下所示:

      protected void Page_Load(object sender, EventArgs e)
      {
        if(!IsPostBack)
         {
          // Validate initially to force asterisks
          // to appear before the first roundtrip.
      
          Dictionary<int, string> dict = new Dictionary<int, string>();
          dict.Add(1, "apple");
          dict.Add(2, "bat");
          dict.Add(3, "cat");
          ddl.DataSource = dict;
          ddl.DataValueField = "Key";
          ddl.DataTextField = "Value";  //will display in ddl
          ddl.DataBind();
         }
      }
      

      【讨论】:

        【解决方案3】:

        Sudha,你可以使用选择地图界面。

        这实际上会满足您的要求,因为它将数据存储在键值对的组合中。

        【讨论】:

        • Rajesh,Java 中的 Map,C# 中的 Dictionary 等价
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多