提供的行索引超出范围。参数名称:index

时间:2016-02-26 10:32:09

标签: c#

当用户选择了项目(多个项目)时,我尝试将所选项目从一个gridview移动到另一个gridview。它读取gridview中的第一行和第三行项目并将其发送到gridview2。

在try catch中给出了上述错误。当用户选择第二行时,如何逐行读取而不跳转到第三行。我已经为此工作了一个星期了。我是C#的初学者。提前谢谢。

    // dgSubjectGridView2 is cleared, first Gridview(dgSubjectGridView) is moving selected item from its grid to dgSubjectGridView2

    private void btnGo_Click(object sender, EventArgs e)
    { 
        dgSubjectGridView2.Rows.Clear();

        try
        {

            DataGridViewRow row = new DataGridViewRow();
        //Counts the total number of rows in dgSubjectGridView
            for (int i = 0; i < dgSubjectGridView.Rows.Count; i++)
            {
                row = dgSubjectGridView.Rows[i];

                Boolean checkstate;

                checkstate = Convert.ToBoolean(row.Cells[0].Value);

                foreach (DataGridViewRow item in dgSubjectGridView.Rows)
                {
                    if (checkstate == true)
                    {

                        dgSubjectGridView2.Rows.Add(false, item.Cells[1].Value.ToString());
                        dgSubjectGridView.Rows.RemoveAt(row.Index);
                    }

                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            //End
        }
    }

1 个答案:

答案 0 :(得分:1)

您似乎在同一个GridView行集合中循环两次。用以下代码替换try块,看看它是否产生了所需的结果。

try
{
    foreach (DataGridViewRow row in dgSubjectGridView.Rows)
    {
        Boolean checkstate = Convert.ToBoolean(row.Cells[0].Value);
        if (checkstate == true)
        {
            dgSubjectGridView2.Rows.Add(false, row.Cells[1].Value.ToString());
            dgSubjectGridView.Rows.RemoveAt(row.Index);
        }

    }
}