[错误] [DataGridView]索引超出范围

时间:2016-08-19 12:44:11

标签: c# datagridview

当我尝试更改“列标题”上的文本时,收到“索引超出范围”错误。请参阅以下代码:

private void cboMonth_TextChanged(object sender, EventArgs e)
{
    dgvAnnual.DataSource = null;
    dgvAnnual.Rows.Clear();
    dgvAnnual.Columns.Clear();

    BindingSource bSource = new BindingSource();
    bSource.DataSource = ReloadData(dtTable, cboMonth.Text);
    dgvAnnual.DataSource = bSource;

    //Testing Code
    Console.WriteLine(dgvAnnual.Columns.Count); //Col = 4
    Console.WriteLine(dgvAnnual.Rows.Count); //Row = 10

    //The Code below is Working
    string[] str = {"Col1","Col2","Col3","Col4"};
    For(int i = 0;i<dvgAnnual.Columns.Count;i++)
    {
        dvgAnnual.Columns[i].HeaderText = str[i];  //<----- It's ok if it's stay in Loop For, event if I replace i by "0"
    }

    //The Code below not working if it stay outside For
    dgvAnnual.Columns[0].HeaderText = "Col1"; //<----- Error if stay alone like this
}

3 个答案:

答案 0 :(得分:0)

工作代码:

    private void cboMonth_TextChanged(object sender, EventArgs e)
    {
       dgvAnnual.DataSource = null;
       dgvAnnual.Rows.Clear();
       dgvAnnual.Columns.Clear();

       BindingSource bSource = new BindingSource();
       bSource.DataSource = ReloadData(dtTable, cboMonth.Text);
       dgvAnnual.DataSource = bSource;

       //Using for testing
       Console.WriteLine(dgvAnnual.Columns.Count); //Col = 4
       Console.WriteLine(dgvAnnual.Rows.Count); //Row = 10

       //This Code below Working
       string[] str = {"Col1","Col2","Col3","Col4"};
       For(int i = 0;i<dvgAnnual.Columns.Count;i++)
       {
           dvgAnnual.Columns[i].HeaderText = str[i];  //<----- It's ok if it's stay in Loop For, event if I replace i by "0"
       }
    }

不工作:

    private void cboMonth_TextChanged(object sender, EventArgs e)
    {
        dgvAnnual.DataSource = null;
        dgvAnnual.Rows.Clear();
        dgvAnnual.Columns.Clear();

        BindingSource bSource = new BindingSource();
        bSource.DataSource = ReloadData(dtTable, cboMonth.Text);
        dgvAnnual.DataSource = bSource;

        //Testing Code
        Console.WriteLine(dgvAnnual.Columns.Count); //Col = 4
        Console.WriteLine(dgvAnnual.Rows.Count); //Row = 10

        //This code below not working
        dgvAnnual.Columns[0].HeaderText = "Col " + 1; //<----- Error: Index out of Range
    }

Watch1上的错误捕获

    +   dgvAnnual.Columns[0]    'dgvAnnual.Columns[0]' threw an exception of type 'System.ArgumentOutOfRangeException'  System.Windows.Forms.DataGridViewColumn {System.ArgumentOutOfRangeException}

由于

答案 1 :(得分:-1)

这里的列的值是4,但是在循环中你的范围是i = 0;到i&lt; = 4表示总数是5.所以改变你的for循环范围。使用i少于dvgAnnual.Columns.count而不是i小于等于dvgAnnual.Columns.count。试试吧。

    for(int i = 0;i<dvgAnnual.Columns.count;i++)
    {
        dvgAnnual.Columns[i].HeaderText = str[i];  //<----- It's ok if it's stay in Loop For, event if I replace i by "0"
    }      

答案 2 :(得分:-1)

解决方案:datagridview必须链接到表单

示例: dgv_Example.Parent = frm_Example