2011-08-24 67 views
2

我有一個表說emp,因爲我沒有任何值。如果我使用此查詢在asp.net編碼中包含「選擇EMP *」:如何從數據庫中獲取數據時出錯信息,但沒有值

con.Open(); 
String str="select * from emp where empname='Abdul'"; 

cmd=new SqlCommand(str,con); 
SqlDataReader dr=cmd.ExecuteReader(); 

while(dr.Read()) 
{ 
    textBox1.text=dr[0].ToString(); 
    textBox2.text=dr[0].ToString(); 
    textBox3.text=dr[0].ToString(); 
} 

con.Close(); 

在EMP表中,我沒有任何empname作爲阿卜杜勒,當我這樣做,它應該表現出一些錯誤,怎麼做?

回答

4

做這樣的事情:

if (dr == null || !dr.HasRows) 
{ 
//NO record found 
    lblError.Text ="No Records Found!"; 
} 
else 
{ 
//Record Found SUCCESS! 
while(dr.Read()) 
{ 
    textBox1.text=dr[0].ToString(); 
    textBox2.text=dr[0].ToString(); 
    textBox3.text=dr[0].ToString(); 
} 

} 

問候

1

不,它不顯示任何錯誤,因爲只有在查詢中有一些結果時才輸入while。

我會使用if/else,如果DataReader沒有內容,因爲沒有找到結果,我會通知用戶或在UI中顯示某些內容,具體取決於應用程序類型和您的確切需求。

+0

你能告訴我怎麼做那個? –

+0

看到從BizApps以上的其他答案,並表決他的解決方案:) –

+0

我投了他,但它顯示投票需要15名聲譽...... –

0

你可以從一個SqlDataAdapter在加載數據到一個DataSet,並使用以下命令:

if (DataSet.Tables[0].Rows.Count <=0) 
{ 

} 
相關問題