【问题标题】:Getting value to stay selected after post back for a drop down list在回发下拉列表后获得价值以保持选中状态
【发布时间】:2014-02-17 05:14:58
【问题描述】:

我的页面加载中有代码背后的代码,它设置了一个下拉列表文本和值。当我选择一个值时,它会重新加载页面,因为我有自动回帖。即使在回发后,我也需要保持选中的值。我该怎么做呢?以下是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
    List<string> list = new List<string>
      { "Month", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};

    DropDownListMonth.DataSource = list;
    DropDownListMonth.DataBind();
    DropDownListMonth.SelectedIndex = 0;

    foreach (ListItem item in DropDownListMonth.Items)
    {
        int i = 0;
        string month = Convert.ToString(i);
        item.Value = month;
        i = Convert.ToInt32(month);
        i++;
    }   
}

【问题讨论】:

  • 如果任何答案解决了您的问题,您应该点击旁边的复选标记接受它。

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


【解决方案1】:

你需要使用IsPostBack()验证:

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack())
    {
        List<string> list = new List<string>
      { "Month", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};

        DropDownListMonth.DataSource = list;
        DropDownListMonth.DataBind();
        DropDownListMonth.SelectedIndex = 0;

        foreach (ListItem item in DropDownListMonth.Items)
        {
            int i = 0;
            string month = Convert.ToString(i);
            item.Value = month;
            i = Convert.ToInt32(month);
            i++;
        }
    }   
}

【讨论】:

  • 感谢您和我阅读的另一页,让它工作。谢谢
  • 很想知道为什么是负分:)
【解决方案2】:
DropDownListMonth.DataSource = list;
DropDownListMonth.DataBind();
DropDownListMonth.SelectedIndex = 0;
string selectedValue=DropDownListMonth.SelectedItem.Tostring();
foreach (ListItem item in DropDownListMonth.Items)
{
       int i = 0;
       string month = Convert.ToString(i);
       item.Value = month;
       i = Convert.ToInt32(month);
       i++;
       if(item.Value.Tostring()==selectedValue)
       {
         item.Selected=true;
       }
}

【讨论】:

    【解决方案3】:

    有一个名为 Page.IsPostBack 的 Page 属性指示页面是第一次呈现还是正在加载以响应回发。

    因此您可以将此属性与if 条件块一起使用,以避免重新绑定ddl。

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
          List<string> list = new List<string>
          { "Month", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
    
        DropDownListMonth.DataSource = list;
        DropDownListMonth.DataBind();
        DropDownListMonth.SelectedIndex = 0;
    
        foreach (ListItem item in DropDownListMonth.Items)
        {
            int i = 0;
            string month = Convert.ToString(i);
            item.Value = month;
            i = Convert.ToInt32(month);
            i++;
        } 
      }  
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多