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

标签 c#

如何修复这个错误:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

在这段代码中:

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

关于c# - 如何修复索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15192813/

相关文章:

c# - C# 的 RDF/OWL/SPARQL/Triple Stores/Reasoners 和其他语义 Web API?

c# - Newtonsoft.Json 在 Unity Editor 中工作,但在移动设备上不工作

c# - Caliburn Micro WPF 窗口管理

c# - 在 C# 中通过服务器同步文件的标准方法?

c# - 如何跨项目和客户端自定义类库配置设置

c# - 从外部javascript函数访问angularJs Controller 方法

c# - C#中属性的不同访问修饰符

c# yield and try-finally 收藏

c# - 反射:递归地搜索字符串值的对象,然后报告路径

c# - 抑制 WinForms WebBrowser 控件的 WaitCursor