如何使用循环从datagridview获取数据

时间:2020-12-24 20:15:48

I am trying to get data from datagridview using for loop i.e take data one by one from row in datagrid and put in listview . but i got an exception "Index was out of range. Must be non-negative and less than the size of the collection parameter name:index" . The data in datagridview is coming from excel sheet .I have following code :

我试图使用for循环从datagridview获取数据,即从datagrid中的行逐个获取数据并放入listview。但我得到一个例外“索引超出范围。必须是非负的并且小于集合参数名称的大小:index”。 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);

}
}

1 个解决方案

#1


3  

You have an off-by-one error in your for loop condition.

你的for循环条件中有一个off-by-one错误。

Change it to use "<" rather than "<=" as shown below.

将其更改为使用“<”而不是“<=”,如下所示。

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

}

#1


3  

You have an off-by-one error in your for loop condition.

你的for循环条件中有一个off-by-one错误。

Change it to use "<" rather than "<=" as shown below.

将其更改为使用“<”而不是“<=”,如下所示。

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

}