在 C# 中从数据表中检索行时出错

本文关键字:检索 出错 数据表 | 更新日期: 2023-09-27 18:36:24

>问题 - 执行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()

在 C# 中从数据表中检索行时出错

您正在尝试用没有任何命令对象与之关联的采用者填充您的DataTable,这就是您返回空结果的原因。您需要创建一个命令对象,然后创建相关的DataAdapater然后使用Fill方法,如下所示:

OleDbCommand selectCommand = new OleDbCommand("select * from yourTable", yourConnection);
OleDbDataAdapter oleDA = new OleDbDataAdapter(selectCommand);

我猜您的查询没有返回任何行。

检查dt.Rows.Count,验证它是否> 0。