2013-02-17 82 views
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 
    } 

讓我將它存儲在stdid1全局變量的ID之後,但我沒有得到存儲在按鈕代碼stdid1變量的值。

protected void Button1_Click(object sender, EventArgs e) 
    { 
     Label1.Text = stdid1.ToString(); 
    } 
+0

爲什麼你首先將它存儲在全局變量中。爲什麼你不能像'Label1.Text = DropDownList1.SelectedValue.ToString()' – ZedBee 2013-02-17 21:26:24

+0

那樣訪問它就是這樣。我從下拉列表中獲得名稱,然後我得到與該名稱表單數據庫相對應的id。 當用戶點擊按鈕進行註冊時,我在註冊表中輸入該ID,因爲它與該表具有外鍵關係。 – 2013-02-17 21:37:15

回答

3

所以stdid1是這個類中的一個字段。變量不會在ASP.NET中的回發中持久化,只要頁面呈現給客戶端,變量就會被釋放。

所以你可以使用ViewStateSession來存儲它。但是我不知道爲什麼當你有DropDownListSelectedValue存在於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只有名字。所以我假設你已經使用了名稱DataTextFieldDataValueField。使用文本的名稱和值的標識。

DropDownList1.DataTextField = "studnt_id"; 
DropDownList1.DataValueField = "name"; 
DropDownList1.DataSource = getStudents(); 
DropDownList1.DataBind(); 
+0

我需要一個其他變量,因爲我從下拉列表中選擇的名稱中獲取「id」。 ,然後使用該ID在用戶按下的按鈕中註冊該人員。 – 2013-02-17 21:30:33

+0

+1 - 絕對ViewState和會話是更好的選擇 – ZedBee 2013-02-17 21:30:38

+0

@MuneebHassan:再次閱讀你的問題後,我已經看到了。但爲什麼你不把ID存儲在'DropDownList'的'SelectedValue'屬性中?您已將該名稱用作DataTextField **和** DataValueField。使用文本的名稱和值的ID。 – 2013-02-17 21:35:15

0

我建議你嘗試移動你的代碼到按鈕單擊事件,而不是SelectedIndexChanged事件,因爲它似乎你並不需要使DB調用直到按鈕被按下實際。

+0

但我可以得到按鈕點擊事件中的下拉列表的選定值? – 2013-02-17 21:31:20

+0

聽Tim在另一個答案中告訴你的是什麼。我會upvote他的答案,是的,你應該能夠訪問下拉列表值。 – 2013-02-17 21:35:20