我有下面這段代碼:的ASP.NET下拉列表的selectedIndex不工作
DataRow CreateRow(DataTable dt, string name, string country)
{
DataRow dr = dt.NewRow();
dr["Name"] = name;
dr["Country"] = country;
return dr;
}
protected void Page_Load(object sender, EventArgs e)
{
// creating the data table
DataTable dt = new DataTable("Student Details");
// adding two columns Name and Country
dt.Columns.Add("Name", typeof(String));
dt.Columns.Add("Country", typeof(String));
// create 3 rows
dt.Rows.Add(CreateRow(dt, "Varun", "India"));
dt.Rows.Add(CreateRow(dt, "Li", "China"));
dt.Rows.Add(CreateRow(dt, "Yishan", "China"));
// create a data view
DataView dv = new DataView(dt);
DropDownList1.DataSource = dv;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Country";
DropDownList1.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = DropDownList1.SelectedIndex;
int temp = 0;
temp++;
}
和標記看起來是這樣的:
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="true">
</asp:DropDownList>
</div>
</form>
</body>
的問題是,標籤總是顯示Varun的不管我選擇的是什麼。我調試了代碼,發現「DropDownList1.SelectedIndex」總是返回0出於某種原因。
我不知道爲什麼會發生這種情況。每當我從下拉列表中選擇某個東西時,函數「DropDownList1_SelectedIndexChanged」就會被調用。
感謝
謝謝c0deNinja!這解決了問題。 – VVV