【问题标题】:No row at position 0 error位置 0 处没有行错误
【发布时间】:2015-09-07 00:24:39
【问题描述】:

我对该主题进行了研究,并遇到了很多关于这个已经问过的问题,但这是不同的情况。

我的 dbConnection 类中有以下代码:

    public void GetCertainComputer(string ComputerBarcode)
    {

        cnn.Open();
        tbl = new DataTable();
        cmd = new SqlCommand(String.Format("exec ComputerInsertUpdateDelete 4, @CompBarcode = '{0}'", ComputerBarcode), cnn);
        reader = cmd.ExecuteReader();

        for (int i = 0; i < reader.FieldCount; i++)
        {
            tbl.Columns.Add(reader.GetName(i));
        }

        while (reader.Read())
        {
            row = tbl.NewRow();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                row[i] = reader[i];
            }

            tbl.Rows.Add(row);
        }

        cnn.Close();
        reader.Close();
        cmd.Dispose();
    }

在我的 MainWindow 中,我调用了这个函数:

db.GetCertainComputer(DGMain.SelectedValue.ToString());

System.Windows.MessageBox.Show(db.tbl.Rows.Count.ToString()); //Row count for Debugging.

txtBarcodeUpd_Computer.Text = db.tbl.Rows[0][0].ToString();
txtDescriptionUpd_Computer.Text = db.tbl.Rows[0][1].ToString();
cbMouseUpd_Computer.SelectedValue = db.tbl.Rows[0][3].ToString();
cbMonitorUpd_Computer.SelectedValue = db.tbl.Rows[0][4].ToString();
cbKeyboardUpd_Computer.SelectedValue = db.tbl.Rows[0][5].ToString();
cbSupplierUpd_Computer.SelectedValue = db.tbl.Rows[0][6].ToString();
cbCourseUpd_Computer.SelectedValue = db.tbl.Rows[0][7].ToString();
cbBranchUpd_Computer.SelectedValue = db.tbl.Rows[0][8].ToString();

消息框返回值 1。因此这意味着函数返回了行。但是,当我在消息框后按 OK 继续时,我收到此错误:

IndexOutOfRangeException No Row at position 0

我不知道为什么它在第二行而不是第一行显示错误,但我也尝试显示 [0][0] 值,但仍然返回并且位置 0 处没有行的错误,是否可能该行可能位于另一个位置?

【问题讨论】:

  • 可以放一个if(db.tbl.Rows.Count &gt; 0 ){ //Do your stuff here. }条件并检查它是否进入了if

标签: c# sql wpf


【解决方案1】:

从您的代码看来,您正在使用DataTable 类实例作为实体数据持有者。我认为您根本不需要使用DataTable。你为什么不拥有一个类Computer,它将包含你将从存储过程中映射的字段。像这样的:

    public class Computer {
    public string <or whatever type it is> Keyboard {get; set;}
        ...
    }

    public IEnumerable<Computer> GetComputers(string ComputerBarcode)
    {
        var computers = new List<Computer>();
        cnn.Open();
        tbl = new DataTable();
        cmd = new SqlCommand(String.Format("exec ComputerInsertUpdateDelete 4, @CompBarcode = '{0}'", ComputerBarcode), cnn);
        reader = cmd.ExecuteReader();



        while (reader.Read())
        {
           computers.Add(new Computer(){ 
                   Keyboard = reader["keyboard"<or whatever your field name for keyboard is>]
               });
        }

        cnn.Close();
        reader.Close();
        cmd.Dispose();

        return computers;
    }

这种将结果从存储过程映射到代码对象的手动工作由许多 ORM 自动完成。 Dapper 是一个很好的例子,而且很容易使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多