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のポストバック間で永続化されず、ページがクライアントにレンダリングされるとすぐに破棄されます。

ViewStateしたがって、それを使用またはSession保存することができます。しかし、とにかくDropDownListを格納するを持っているのに、なぜ別の変数が必要なのかわかりません。SelectedValueViewState

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

ASP.NETアプリケーションで永続的なユーザー状態を管理するための9つのオプション

アップデート

もう一度質問を読んだ後、IDをその変数に格納したいのですが、DropDownListには名前しかありません。DataTextField したがって、と の両方に名前を使用したと思いますDataValueField。テキストには名前を使用し、値にはIDを使用します。

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

ボタンが実際に押されるまでDB呼び出しを行う必要がないように思われるため、コードをselectedindexchangedイベントではなくボタンクリックイベントに移動してみることをお勧めします。

于 2013-02-17T21:28:29.907 に答える