0

问题是我从下拉列表中获取名称,然后从表中获取该名称的学生 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();
    }
4

2 回答 2

3

stdid1此类中的一个字段也是如此。变量不会在 ASP.NET 中的回发中保留,它们会在页面呈现给客户端后立即释放。

所以你可以使用ViewStateSession存储它。但是我不知道为什么当你有一个无论如何都DropDownList需要存储的SelectedValue时候你需要另一个变量。ViewState

protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = DropDownList1.SelectedValue;
}

在 ASP.NET 应用程序中管理持久用户状态的九个选项

更新

再次阅读您的问题后,我看到您想将 ID 存储在该变量中,但DropDownList只有名称。所以我假设你已经使用了DataTextField DataValueField的名称。使用文本的名称和值的 id。

DropDownList1.DataTextField  = "studnt_id";
DropDownList1.DataValueField = "name";
DropDownList1.DataSource = getStudents();
DropDownList1.DataBind();
于 2013-02-17T21:27:46.463 回答
0

我建议您尝试将代码移动到按钮单击事件而不是 selectedindexchanged 事件中,因为在实际按下按钮之前您似乎不需要进行 DB 调用。

于 2013-02-17T21:28:29.907 回答