我在我的项目中使用c#和asp.net。我想得到下拉列表的selectedindex,但我总是得到0.这是我的下拉列表与数据绑定的代码
MySqlDataReader dr = null;
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select category from lk_category";
MySqlCommand command = mycon.CreateCommand();
command.CommandText = str;
dr = command.ExecuteReader();
DropDownList1.DataSource = dr;
DropDownList1.DataValueField = "category";
DropDownList1.DataBind();
dr.Close();
str = "select technology from lk_technology";
command.CommandText = str;
dr = command.ExecuteReader();
DropDownList2.DataSource = dr;
DropDownList2.DataValueField = "technology";
DropDownList2.DataBind();
}
catch (Exception ex) { Response.Write("Exception reding data" + ex); }
finally
{
//dr.Close();
mycon.Close();
}
我正试图通过以下方式获得选择索引:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
catID = DropDownList1.SelectedIndex+1;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
techID = DropDownList2.SelectedIndex;
}
这是我的page_load:
protected void Page_Load(object sender,EventArgs e) {
if (Session["valid"] == null)
Response.Redirect("admin.aspx");
panel1();///If session valid then show panel1;
}
请告诉我哪里出错了。
答案 0 :(得分:1)
这是因为你在页面加载中重新填充下拉列表而不检查它是否没有回发。
使用
变形try-catch(下拉填充)代码if (!this.IsPostBack)
{
...
}
应该解决问题。