簡體   English   中英

回傳下拉列表后獲得選擇的價值

[英]Getting value to stay selected after post back for a drop down list

我在頁面加載中有代碼背后的代碼,該代碼設置了下拉列表的文本和值。 每當我選擇一個值時,它都會重新加載頁面,因為我已經自動回發了。 即使回發后,我也需要保持選擇的值。 我將如何去做呢? 下面是我的代碼:

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++;
    }   
}

有一個名為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++;
    } 
  }  
}

您需要使用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++;
        }
    }   
}
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;
       }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM