2014-01-19 168 views
1

誤差線:[InvalidCastException的:無法轉換類型 'System.DBNull' 的目的爲類型 'System.String']

源錯誤:

Line 37:   while (rdr.Read()==true) 
Line 38:   { 
Line 39:    if (TextBoxUserName.Text == (string)rdr["CUserName"]) 
Line 40:    { 
Line 41:     ClientScript.RegisterStartupScript(csType,"Error",scriptErrorUserId); 

它彈出時,我試圖註冊一個帳戶。

我使用Microsoft Access作爲數據庫。

數據庫 - CUserName 會議 - sUserName 和有@eUserName

任何想法的傢伙?

回答

3

替換此

if (TextBoxUserName.Text == (string)rdr["CUserName"]) 

if (TextBoxUserName.Text == rdr["CUserName"].ToString()) 
1

在將其轉換爲string之前,您需要先檢查rdr["CUserName"]是否等於System.DBNull.Value。更改此:

if (TextBoxUserName.Text == (string)rdr["CUserName"]) 

這樣:

string userName = rdr["CUserName"] != System.DBNull.Value ? (string)rdr["CUserName"] : string.Empty; 
if (TextBoxUserName.Text == userName) 
+0

此致意義,但其他人的答案解決它。我沒有嘗試過你的,因爲我認爲它不需要!= system.dbnull.value呃? –

+1

對於字符串數據類型,您可能不需要檢查'!= System.DBNull.Value',但您需要將其用於其他數據類型,即decimal或integer。 – ekad

+0

啊對了,謝謝你的信息:) –

相關問題