C# 检查数据读取器在 Asp.net 中是否有行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10859919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a datareader has rows or not in Asp.net
提问by devan
My code:
我的代码:
string sqlQuery1 = "select * from employees where depid=6";
SqlDataReader Dr1 = dbconn.RunQueryReturnDataReader(sqlQuery1);
if(Dr1.read()) { //or if (Dr1["empname"] != DBNull.Value)
while (Dr1.Read())
{
Label1.Text = Dr1["empname"].ToString();
Label2.Text = Dr1["empdes"].ToString();
...
}
Dr1.Close();
}
else {
Label1.text = "defaultValue";
Label2.text = "defaultValue";
...
}
I just want to check SqlDataReader has no records to display. If no records ,the labels should showdefault values preassigned by me or If has record display datareader value on label. (Assume either SqlDataReader has 1 recode or has norecord only)
我只想检查 SqlDataReader 没有要显示的记录。如果没有记录,标签应该显示我预先分配的默认值,或者如果标签上有记录显示数据读取器值。(假设 SqlDataReader 有 1 个重新编码或只有 norecord)
How can I check first datareader hasRow or not?
如何检查第一个数据读取器 hasRow 与否?
I have tried two ways as above code.
我已经尝试了上面代码的两种方法。
if(Dr1.read())- this way working fine. But after executeIfstatement ,it has no value to display on labels , since read() will increase the pointer. As a result label1 ,Label2.. Nothing display.if (Dr1["empname"] != DBNull.Value)This way generate an exception when Sqldatareader has norows.
if(Dr1.read())- 这样工作正常。但是在执行If语句之后,它没有值显示在标签上,因为 read() 会增加指针。结果 label1 ,Label2.. 什么都没有显示。if (Dr1["empname"] != DBNull.Value)当 Sqldatareader 有 norows 时,这种方式会生成异常。
error: System.InvalidOperationException: Invalid attempt to read when no data is present
error: System.InvalidOperationException: Invalid attempt to read when no data is present
Please help me. tx
请帮我。发送
采纳答案by Ray Cheng
try...
尝试...
if(Dr1.HasRows)
{
//....
}
回答by Nikhil D
if (Dr1 == null || !Dr1.HasRows) {
// Do something
}

