[英]No row at position 0 Error Handing
我有以下代码:
try
{
connection.Open();
da.Fill(ds);
DataRow item = ds.Tables[0].Rows[0];
byte[] item1 = (byte[])item["FileImage"];
ds.Tables.Clear();
numArray = item1;
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
return numArray;
}
我的代码通过将GridView中的ID传递到SQL语句中来工作,以便找到与存储在表上的ID相关联的对应FileImage。 我最近注意到,如果手动输入错误的ID,站点将崩溃,并引发异常“位置0处无行”,我发现这基本上意味着没有数据可提取(显然是因为我输入了伪造的ID)。
我的问题是如何处理此错误? 我以前从未真正考虑过错误处理,但我想从我读到的内容中我会做一些诸如if语句的事情? 基本上,如果没有异常,则继续进行,但是,如果有异常,则可以将页面上TextBox的文本更改为错误消息,告诉用户“警告! ID无效”?
谢谢你的帮助!
您可能在这里得到错误:
DataRow item = ds.Tables[0].Rows[0];
因为此索引处没有行,所以表中根本没有行。
您只需要使用Count
属性进行检查:
if(ds.Tables[0].Rows.Count > 0)
{
}
如果没有返回行,则表也为空。 Tables
属性还具有Count
属性。
if(ds.Tables.Count > 0)
{
}
您需要先验证是否有数据,然后再检索它。
更换:
DataRow item = ds.Tables[0].Rows[0];
byte[] item1 = (byte[])row["FileImage"];
与
byte[] item1 = null;
if (ds.Tables.Count > 0)
{
var table = ds.Tables[0];
if (table.Rows.Count > 0)
{
var row = table.Rows[0];
if (row.Columns.Contains("FileImage"))
{
item1 = (byte[])row["FileImage"];
}
}
}
if (item1 == null)
{
//handle error
}
您不必在catch代码块中引发异常(根据您在发布的代码中看到的内容)。
您可以简单地显示一条消息,指出发生了如下问题:
try
{
connection.Open();
da.Fill(ds);
DataRow item = ds.Tables[0].Rows[0];
byte[] item1 = (byte[])item["FileImage"];
ds.Tables.Clear();
numArray = item1;
}
catch (Exception ex)
{
MessageBox.Show("My error description");
// or write the message to a textBox.
}
finally
{
connection.Close();
}
return numArray;
}
你可以做
try
{
// your code....
}
catch (Exception ex)
{
MessageBox.Show("My method failed, see inner excpetion",ex);
}
finally
{
connection.Close();
}
return numArray;
}
您需要查看.Rows
包含元素。
if (ds.Tables[0].Rows.Any())
{
// Has rows.
}
您应该检查是否有要处理的行。 像这样:
try
{
connection.Open();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
DataRow item = ds.Tables[0].Rows[0];
byte[] item1 = (byte[])item["FileImage"];
ds.Tables.Clear();
numArray = item1;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
return numArray;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.