亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

解決DropDownList總是選中第一項(xiàng)的方法

 更新時(shí)間:2015年10月08日 11:33:14   投稿:lijiao  
這篇文章主要介紹了解決DropDownList總是選中第一項(xiàng)的方法,DropDownList下拉框服務(wù)器控件是最常用的控件之一,雖然使用方便,但也會(huì)出現(xiàn)奇怪的錯(cuò)誤,感興趣的小伙伴們可以參考一下

在網(wǎng)頁開發(fā)的過程中,在頁面中使用了一個(gè) DropDownList 服務(wù)器控件,發(fā)現(xiàn)了一個(gè)很奇怪的問題,不論在頁面中選中哪一項(xiàng),在后臺(tái)獲取到的值總是第一項(xiàng)的值,看了好久也沒有發(fā)現(xiàn)問題出在哪里,DropDownList控件在開發(fā)中已經(jīng)使用了無數(shù)遍了,對(duì)照了其他代碼都是一樣的!

經(jīng)過了幾分鐘之后,實(shí)在是看不出問題在哪里只好到網(wǎng)上查找答案,網(wǎng)上果然有不少人遇到“一樣”的問題—— DropDownList 總是選中第一項(xiàng)。網(wǎng)上的解決方法都是說在 DropDownList 綁定時(shí)要在 Page_Load 事件要使用 if(!IsPostBack),可是我是這樣綁定的,在網(wǎng)上還是沒有找到解決的方法。

后來,自己靜靜地左思右想,是不是因?yàn)樽约涸诮壎―ropDownList 的時(shí)候,只給Text 賦值,而沒有給 Value 賦值導(dǎo)致的呢?接著我就嘗試把每一項(xiàng)的Value 賦值,果然沒有這樣的現(xiàn)象了!

現(xiàn)在總結(jié) DropDownList 控件總是選中第一項(xiàng)的兩種原因。

情況一,請(qǐng)看下面的代碼:
客戶端代碼:

<asp:DropDownListID="ddl1"runat="server">
</asp:DropDownList>

服務(wù)端代碼:

protected void Page_Load(object sender, EventArgs e)
{
  BindDropDownList();
}
  
private void BindDropDownList()
{
  ddl1.Items.Clear(); //每次綁定前,先清除所有項(xiàng)
  for (int i = 1; i <= 3; i++)
  {
    ListItem item1 = new ListItem();
    item1.Text = "第" + i.ToString() + "項(xiàng)";
    item1.Value = "第" + i.ToString() + "項(xiàng)";
    ddl1.Items.Add(item1);
  }
}

上面代碼案例,也就是網(wǎng)上說的總是選中第一項(xiàng)(選擇不能改變選項(xiàng)),綁定方法寫在 if (!IsPostBack) 里就可以解決了,代碼如下:

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    BindDropDownList();
  }
}

情況二,即是筆者遇到的,請(qǐng)看下面的代碼:
客戶端代碼:

<asp:DropDownList ID="ddl1" runat="server">
</asp:DropDownList>
&nbsp;<asp:Button ID="btnGet" runat="server" Text="獲取" onclick="btnGet_Click" />

服務(wù)端代碼:

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    BindDropDownList();
  }
}
  
private void BindDropDownList()
{
  ddl1.Items.Clear(); //每次綁定前,先清除所有項(xiàng)
  for (int i = 1; i <= 3; i++)
  {
    ListItem item1 = new ListItem();
    item1.Text = "第" + i.ToString() + "項(xiàng)";
    item1.Value = "";
    ddl1.Items.Add(item1);
  }
}
  
protected void btnGet_Click(object sender, EventArgs e)
{
  string str = ddl1.SelectedItem.Text;
  Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('" + str + "');</script>");
}

注意 item1.Value 這個(gè)地方,是沒有賦值的,然而導(dǎo)致獲取 Text 的值錯(cuò)亂了,只要給 Value 賦上值就沒有問題了!

以上就是關(guān)于網(wǎng)上大多數(shù)人遇到“一樣”的問題—— DropDownList 總是選中第一項(xiàng)的解決辦法,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論