【问题标题】:How to fix Index Out Of Range error如何修复索引超出范围错误
【发布时间】:2013-03-04 00:44:09
【问题描述】:

我该如何解决这个错误:

索引超出范围。必须是非负数且小于集合的大小。 参数名称:索引

在这段代码中:

dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns.Add("ID", "ID");
dataGridView1.Columns.Add("Firstname", "Firstname");
dataGridView1.Columns.Add("MI", "MI");
dataGridView1.Columns.Add("Lastname", "Lastname");
dataGridView1.Columns.Add("Username", "Username");
dataGridView1.Columns.Add("Rights", "Rights");
c.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = c;
cmd.CommandText = "SELECT * From Account";
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["ID"].Value = reader[0].ToString();
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Firstname"].Value = reader[1].ToString();
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["MI"].Value = reader[2].ToString();
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Lastname"].Value = reader[3].ToString();
    dataGridView1.Rows[dataGridView1.Rows.Count -    1].Cells["Username"].Value = reader[7].ToString();
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Rights"].Value      = reader[9].ToString();
}
c.Close();

【问题讨论】:

  • Account表的结构是什么?
  • 哪一行会报错?该行上的对象的运行时状态是什么?
  • 为什么不使用dataBind?
  • @lexter 提供了一个使用数据绑定的示例,这是解决问题的简单方法。您收到索引超出范围错误的原因是您引用了尚未添加的行,因此 Rows.Count-1 等于 -1。

标签: c#


【解决方案1】:

您是否尝试将数据库中的数据显示到datagridview?为什么不使用databind

查看我的示例代码:

string connStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=the directory or the path of your database";
string query = "SELECT * From Table Name";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
    using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
    {
        DataSet ds = new DataSet();
        adapter.Fill(ds);
        dataGridView1.DataSource = ds.Tables[0];
    }
    conn.Close();
}

【讨论】:

  • @AlfredSanz - 你是什么意思? ds 是DataSet
【解决方案2】:

Rows 集合有一个“Add”方法,它接受一个对象数组。与您问题中的代码示例相比,这绝对是一种更简单、更直接的方法:

http://msdn.microsoft.com/en-us/library/fbs04kbx.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-30
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多