【问题标题】:Insert data in datagridview gives exception在 datagridview 中插入数据会出现异常
【发布时间】:2010-10-18 12:59:12
【问题描述】:

我想使用 datagridview 向用户显示一些数据(信息)。我的 datagridview 有 4 列。当我使用此代码时

private void sfactor_Load(object sender, EventArgs e)
{
        dataGridView1.Rows[0].Cells[0].Value = "book";
        dataGridView1.Rows[1].Cells[0].Value = "pen";
        dataGridView1.Rows[2].Cells[0].Value = "x";
        dataGridView1.Rows[3].Cells[0].Value = "y";
        dataGridView1.Rows[4].Cells[0].Value = "z";
}

我想在column[0] 中显示此信息。程序运行时出现异常:

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

我知道为什么,但我不知道如何解决它。现在我需要你的帮助和你的经验。我等着你的回答。

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:

    您想创建一个数据表并填写它。

    然后您可以使用 datagridview 的 datasource 属性将您的数据表绑定到 datagridview。

    【讨论】:

      【解决方案2】:

      您需要在分配值之前创建行。有一个重载可让您同时创建和设置值:

          dataGridView1.Rows.Add("book");
          dataGridView1.Rows.Add("pen");
          dataGridView1.Rows.Add("x");
          dataGridView1.Rows.Add("y");
          dataGridView1.Rows.Add("z");
      

      【讨论】:

      • 如果我想在 row[3] 和 column[4] 中添加“x”,我可以在哪里输入行数和列数?
      • @mahnaz 添加行后,您可以按索引对其进行寻址。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      相关资源
      最近更新 更多