【问题标题】:How to get data from datagridview using loop如何使用循环从datagridview获取数据
【发布时间】:2015-08-05 22:36:57
【问题描述】:

我正在尝试使用 for 循环从 datagridview 获取数据,即从 datagrid 中的行一个接一个地获取数据并放入 listview 。但我有一个例外 “索引超出范围。必须为非负数且小于集合参数名称的大小:索引”。 datagridview 中的数据来自 excel 表。我有以下代码:

private void button1_Click(object sender, EventArgs e)
 {
listView1.Visible = true;
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;

//Add column header
listView1.Columns.Add("Recipent Number", 500);
listView1.Columns.Add("Status", 100);

for (int i = 0; i <= dataGridView1.RowCount; i++)
{
    //Add items in the listview
    string[] arr = new string[2];
    ListViewItem itm;

    //Add first item
    arr[0] = dataGridView1.Rows[i+1].Cells["F1"].Value.ToString();
    arr[1] = "Send";
    itm = new ListViewItem(arr);
    listView1.Items.Add(itm);

}
}

【问题讨论】:

  • 通过它调试时,哪一行会抛出错误?
  • 这是 C# 而不是 VB.NET。请删除 VB.NET 标记。
  • 对不起!我要删除

标签: c# excel datagridview


【解决方案1】:

您的 for 循环条件中有一个错误。

如下所示,将其改为使用“

for (int i = 0; i < dataGridView1.RowCount; i++)
{
    //Add items in the listview
    string[] arr = new string[2];
    ListViewItem itm;

    //Add first item
    arr[0] = dataGridView1.Rows[i+1].Cells["F1"].Value.ToString();
    arr[1] = "Send";
    itm = new ListViewItem(arr);
    listView1.Items.Add(itm);

}

【讨论】:

  • ..并将dataGridView1.Rows[i+1]更改为dataGridView1.Rows[i]
  • 谢谢@Prashant!你让我的夜晚:)
  • 谢谢@JacobSeleznev :) 你也度过了我的夜晚:P
猜你喜欢
  • 2020-01-22
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 2023-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多