[英]Error in retrieving rows from DataTable in C#
問題 - 在MessageBox.Show("for loop, last row..."); //TEST CODE
行之后出現錯誤MessageBox.Show("for loop, last row..."); //TEST CODE
MessageBox.Show("for loop, last row..."); //TEST CODE
執行。 可能是什么原因 ? 當我從另一個數據庫獲取結果集時,沒有這樣的問題。 :( 我該如何解決 ?
代碼 -
public void Main()
{
OleDbDataAdapter oleDA = new OleDbDataAdapter();
DataTable dt = new DataTable();
DataColumn col = null;
DataRow row = null;
string strCols = "";
oleDA.Fill(dt, Dts.Variables["MyResultSet"].Value);
col = dt.Columns["MyColumn"];
int lastIdx = dt.Rows.Count - 1;
MessageBox.Show("int declared, for loop..."); //TEST CODE
//loop upto 2nd last data row
for (int i = 0; i <= lastIdx-1; i++)
{
row = dt.Rows[i];
strCols += row[col.Ordinal].ToString() + ", ";
}
MessageBox.Show("for loop, last row..."); //TEST CODE
row = dt.Rows[lastIdx];
strCols += row[col.Ordinal].ToString(); //!!! I GET ERROR HERE !
MessageBox.Show("strCols");
Dts.TaskResult = (int)ScriptResults.Success;
}
錯誤 -
Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IndexOutOfRangeException: There is no row at position -1.
at System.Data.RBTree`1.GetNodeByIndex(Int32 userIndex)
at System.Data.RBTree`1.get_Item(Int32 index)
at System.Data.DataRowCollection.get_Item(Int32 index)
at My-Long-Code-Goes-Here.csproj.ScriptMain.Main()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
我猜你的查詢沒有返回任何行。
檢查dt.Rows.Count
,驗證它是否> 0。
您正在嘗試使用沒有與之關聯的任何命令對象的采用者填充您的DataTable
,這就是為什么您將獲得空結果。 您需要創建一個命令對象,然后創建相關的DataAdapater
,然后使用Fill
方法,如:
OleDbCommand selectCommand = new OleDbCommand("select * from yourTable", yourConnection);
OleDbDataAdapter oleDA = new OleDbDataAdapter(selectCommand);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.