在網(wǎng)頁開發(fā)的過程中,在頁面中使用了一個 DropDownList 服務器控件,發(fā)現(xiàn)了一個很奇怪的問題,不論在頁面中選中哪一項,在后臺獲取到的值總是第一項的值,看了好久也沒有發(fā)現(xiàn)問題出在哪里,DropDownList控件在開發(fā)中已經(jīng)使用了無數(shù)遍了,對照了其他代碼都是一樣的!
經(jīng)過了幾分鐘之后,實在是看不出問題在哪里只好到網(wǎng)上查找答案,網(wǎng)上果然有不少人遇到“一樣”的問題—— DropDownList 總是選中第一項。網(wǎng)上的解決方法都是說在 DropDownList 綁定時要在 Page_Load 事件要使用 if(!IsPostBack),可是我是這樣綁定的,在網(wǎng)上還是沒有找到解決的方法。
后來,自己靜靜地左思右想,是不是因為自己在綁定DropDownList 的時候,只給Text 賦值,而沒有給 Value 賦值導致的呢?接著我就嘗試把每一項的Value 賦值,果然沒有這樣的現(xiàn)象了!
現(xiàn)在總結 DropDownList 控件總是選中第一項的兩種原因。
情況一,請看下面的代碼:
客戶端代碼:
asp:DropDownListID="ddl1"runat="server">
/asp:DropDownList>
服務端代碼:
protected void Page_Load(object sender, EventArgs e)
{
BindDropDownList();
}
private void BindDropDownList()
{
ddl1.Items.Clear(); //每次綁定前,先清除所有項
for (int i = 1; i = 3; i++)
{
ListItem item1 = new ListItem();
item1.Text = "第" + i.ToString() + "項";
item1.Value = "第" + i.ToString() + "項";
ddl1.Items.Add(item1);
}
}
上面代碼案例,也就是網(wǎng)上說的總是選中第一項(選擇不能改變選項),綁定方法寫在 if (!IsPostBack) 里就可以解決了,代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
}
}
情況二,即是筆者遇到的,請看下面的代碼:
客戶端代碼:
asp:DropDownList ID="ddl1" runat="server">
/asp:DropDownList>
nbsp;asp:Button ID="btnGet" runat="server" Text="獲取" onclick="btnGet_Click" />
服務端代碼:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
}
}
private void BindDropDownList()
{
ddl1.Items.Clear(); //每次綁定前,先清除所有項
for (int i = 1; i = 3; i++)
{
ListItem item1 = new ListItem();
item1.Text = "第" + i.ToString() + "項";
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 這個地方,是沒有賦值的,然而導致獲取 Text 的值錯亂了,只要給 Value 賦上值就沒有問題了!
以上就是關于網(wǎng)上大多數(shù)人遇到“一樣”的問題—— DropDownList 總是選中第一項的解決辦法,希望對大家的學習有所幫助。
您可能感興趣的文章:- 基于Jquery的將DropDownlist的選中值賦給label的實現(xiàn)代碼
- 深入DropDownList用法的一些學習總結分析
- ASP.NET DropDownListCheckBox使用示例(解決回發(fā)問題)
- DropDownList綁定數(shù)據(jù)表實現(xiàn)兩級聯(lián)動示例
- DropDownList獲取的SelectIndex一直為0的問題
- ASP.NET MVC中為DropDownListFor設置選中項的方法
- JS簡單操作select和dropdownlist實例
- C#動態(tài)生成DropDownList執(zhí)行失敗原因分析
- DropDownList設置客戶端事件思路