asp.net中的下拉列表项选择

时间:2013-05-09 12:03:36

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

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

 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中选择了什么价值,它总是得到&#39; 1&#39;在关键和&#34;苹果&#34;价值。我的代码出了什么问题?

3 个答案:

答案 0 :(得分:3)

这是因为你将每个帖子的列表绑定回来,你应该检查IsPostBack喜欢

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

答案 1 :(得分: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();
   }
}

答案 2 :(得分:1)

Sudha,你可以选择Map界面。

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