[英]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.