2013-07-29 81 views
1

我是新來的WPF。我得到以下錯誤:「爲System.Data.Common.DbDataReader.GetInt32的最佳重載消息匹配具有一些無效參數」從數據庫讀取時出錯

我的代碼如下:

private void comboBoxDisplay_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     string constring = "Data Source=tcp:******.database.windows.net;Initial  Catalog=*****;Persist Security Info=True;User ID=*****;Password=******"; 

     string Query = "select * from Rewards where Name='" + comboBoxDisplay.Text + "' ;"; 
     SqlConnection conDataBase = new SqlConnection(constring); 
     SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase); 
     SqlDataReader myReader; 

     try 
     { 
      conDataBase.Open(); 
      myReader = cmdDataBase.ExecuteReader(); 

      while (myReader.Read()) 
      { 

       string sReid = myReader.GetInt32(0).ToString(); 
       string sName = myReader.GetString(1); 



      } 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     }` 

回答

0

的System.Data.Common .DbDataReader.GetInt32方法期望一個整數,它是列的序號。沒有重載的方法將字符串作爲參數。

myReader.GetInt32(2); // gets the 3rd column (zero based) 
+0

這擺脫了錯誤,但是當我從組合框中選擇的值不顯示在文本框中。 – user2631662

1

GetXXX方法使用列號而不是名稱。如果你正在調用正確的方法,你也不需要投。試試這個

while (myReader.Read()) 
     { 

      string sReid = myReader.GetString(myReader.GetOrdinal("reID")); 
      string sName = myReader.GetString(myReader.GetOrdinal("Name")); 


     } 
+0

無法識別GetOrdinal – user2631662

+0

我修改了我的代碼來解決此問題。對這個錯誤感到抱歉。注意一下:你可能應該在try/catch中包含這些,以防錯誤(列名錯誤,數據庫格式不正確等)。 – steveg89

+0

謝謝!你知道爲什麼我會從文本框中顯示組合框中以前選擇的項目的值而不是實際選定的項目嗎? – user2631662