Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何修复索引超出范围错误_C# - Fatal编程技术网

C# 如何修复索引超出范围错误

C# 如何修复索引超出范围错误,c#,C#,如何修复此错误: 索引超出范围。必须为非负数且小于集合的大小。 参数名称:索引 在此代码中: dataGridView1.AllowUserToAddRows = false; dataGridView1.Columns.Add("ID", "ID"); dataGridView1.Columns.Add("Firstname", "Firstname"); dataGridView1.Columns.Add("MI", "MI"); dataGridView1.Columns.Add("Las

如何修复此错误:

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

在此代码中:

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();

您正在尝试将数据从数据库显示到
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();
}

Rows集合有一个接受对象数组的“Add”方法。问题中的代码示例显然是一种更简单、更直接的方法:


科目表的结构是什么?哪一行抛出错误?该行上对象的运行时状态是什么?为什么不使用数据绑定?lexter提供了一个使用数据绑定的示例,这是解决问题的简单方法。获取索引超出范围错误的原因是您引用的行尚未添加,因此
行。Count-1
等于-1。@AlfredSanz-这是什么意思?ds是
数据集