问题是我从下拉列表中获取名称,然后从表中获取该名称的学生ID。
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
stud_name1 = ddl.SelectedValue;// sends the value
// Label1.Text = ddl.SelectedValue;
string getquery = "select studnt_id from Student where name='"+stud_name1+"'";
getidcon.Open();
SqlCommand getid = new SqlCommand(getquery, getidcon);
stdid1 = ((int)getid.ExecuteScalar());// gives the id in return to selection
// Session [stdid1]
// Label1.Text = stdid1.ToString();// testing value
// get the roll number
}
获取id之后,我将它存储在stdid1全局变量中,但是我没有在按钮代码中获得存储在stdid1变量中的值。
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = stdid1.ToString();
}
答案 0 :(得分:3)
所以stdid1
是这个类中的一个字段。 ASP.NET中的回发不会保留变量,只要页面呈现给客户端,它们就会被释放。
因此,您可以使用ViewState
或Session
来存储它。但是,当你有DropDownList
将SelectedValue
存储在ViewState
时,我不知道为什么你需要另一个变量。
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedValue;
}
Nine Options for Managing Persistent User State in Your ASP.NET Application
<强>更新强>
再次阅读您的问题之后,我发现您希望将ID存储在该变量中,但DropDownList
只有名称。因此,我假设您已使用DataTextField
和 DataValueField
的名称。使用文本名称和值的id。
DropDownList1.DataTextField = "studnt_id";
DropDownList1.DataValueField = "name";
DropDownList1.DataSource = getStudents();
DropDownList1.DataBind();
答案 1 :(得分:0)
我建议您尝试将代码移动到按钮单击事件而不是selectedindexchanged事件,因为在实际按下按钮之前,您似乎不需要进行数据库调用。