2016-06-17 35 views
0

在用戶界面中,我有包含(一級,二級,三級)的單選按鈕列表。另一方面,我有學生表(ID,名稱,級別,DOB,....),它將學生的級別保存爲varchar。 在頁面加載時,我想根據從數據庫讀取的值填充radioButtonList。 下面的代碼正在運行,但它不檢查從數據庫中讀取的適當的單選按鈕。根據從數據庫中讀取的文本值檢查RadioButtonList中的單選按鈕

using (MySqlConnection SqlCon = new MySqlConnection(connStr)) 
       { 
        MySqlDataReader myReader = null; 
        using (MySqlCommand cmd = new MySqlCommand("SELECT S_Id, level FROM student where S_Id='" + 111 + "'")) 
        { 
         cmd.CommandType = CommandType.Text; 
         cmd.Connection = SqlCon; 
         SqlCon.Open(); 
         myReader = cmd.ExecuteReader(); 
         if (RadioButtonList1.Items.FindByValue(myReader.ToString()) != null) 
         { 
          // RadioButtonList1.Items.FindByValue(myReader.ToString()).Selected = true; 
          RadioButtonList1.SelectedValue = myReader.ToString(); 
         } 

         SqlCon.Close(); 
        } 
       } 
+0

是你的代碼,你打電話從數據庫中獲取數據是在回發檢查? – riteshmeher

+0

是的,我把這個代碼放在裏面:if(!this.IsPostBack){... My Code ...} – John

+0

radioButtonList1.Items.FindByText(「Your Text」)。Selected = true;或者您也可以使用Items Index RadioButtonList.Items [1] .Selected = true; –

回答

0

您必須遍歷DataReader對象以獲取其值。嘗試這樣的:

using (MySqlConnection SqlCon = new MySqlConnection(connStr)) 
{ 
    MySqlDataReader myReader = null; 
    using (MySqlCommand cmd = new MySqlCommand("SELECT S_Id, level FROM student where S_Id='" + 111 + "'")) 
{ 
    cmd.CommandType = CommandType.Text; 
    cmd.Connection = SqlCon; 
    SqlCon.Open(); 
    myReader = cmd.ExecuteReader(); 
    while (myReader.Read()) 
    { 
    if (RadioButtonList1.Items.FindByValue(myReader["level"].ToString()) != null) 
    {       
    RadioButtonList1.SelectedValue = myReader["level"].ToString(); 
    }    
    } 
    sqlCon.Close(); 
} 
} 
相關問題