當我嘗試更改列標題上的文本時,收到「索引超出範圍」錯誤。請參閱下面的代碼:[錯誤] [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
}
For(int i = 0; i <= dvgAnnual.Columns.count; i ++)應該是'<'!當然是'計數'.. – TaW
您的代碼至少有2個錯誤,不會編譯或使其崩潰。請發佈[mcve]。 – nvoigt
@Taw我的失敗了,我的代碼是正確的 –