2016-06-25 112 views
0

我正在使用下面的函數從數據庫中獲取值。錯誤無法將類型'System.Int32'的對象轉換爲鍵入'System.String'

問題是當我選擇int類型的列。

我得到這個錯誤Unable to cast object of type 'System.Int32' to type 'System.String'.

在這一行result.Add(dr.GetString(0));

代碼

[WebMethod] 
public static List<string> GetAutoCompleteData(string value, string filterBy) 
{ 
    string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString; 
    using (SqlConnection con = new SqlConnection(strConnString)) 
    { 
     con.Open(); 
     string command = string.Format("select {0} from Users where {0} LIKE '%'[email protected]+'%'", filterBy); 
     using (SqlCommand cmd = new SqlCommand(command, con)) 
     { 
      cmd.Parameters.AddWithValue("@SearchText", value); 

      using (SqlDataReader dr = cmd.ExecuteReader()) 
      { 
       List<string> result = new List<string>(); 
       while (dr.Read()) 
       { 
        result.Add(dr.GetString(0)); 
       } 
       return result; 
      } 
     } 
    } 
} 

用戶表結構

UserID type int 
UserName type nvarchar(50) 
Password type nvarchar(50) 
+0

你能告訴我們你的表結構嗎? –

回答

2

嘗試result.Add(dr.GetValue(0).ToString());

要避免的GetValue()是空的回報,做到這一點 -

result.Add((sqlreader.IsDBNull(0) ? "" : dr.GetValue(0).ToString()); 
+1

你能解釋一下爲什麼答案是這樣嗎?如果你沒有解釋它,如何解決和爲什麼解決這個問題,那麼對任何人來說都不是非常有幫助的。 – Li357

+0

它解決了我的問題 – Ayman

+0

很好。如果它解決了您的問題,請選擇答案。謝謝 –

8

when i select column of type int

根據代碼,你要選擇string類型的列:

dr.GetString(0) 

如果列是int,然後得到一個int

dr.GetInt32(0) 

,然後可以轉換爲string爲您的列表:

result.Add(dr.GetInt32(0).ToString()); 

具體有關錯誤,請注意文本the documentation

No conversions are performed; therefore, the data retrieved must already be a string.

+0

這應該被標記爲答案,因爲它很好地解釋了問題,並解釋瞭解決方案 –

0

我面臨同樣的類型的錯誤:'System.Int32'鍵入'System.String'

在這裏,如果你要綁定的字符串值意味着

dr.GetString(1) 

要麼,如果你要打印的int值意味着

dr.GetInt32(0) 

我得到了一個更錯誤:指定的轉換是無效的。

如果你想字符串意味着ü需要把

dr.GetString(1) 

最初我做dr.GetString(0)這說明指定的轉換無效。 同樣的事情,如果你需要int值意味着你需要把dr.GetInt32(0)dr.GetInt32(1)

相關問題