C#datagridview参数超出范围异常

时间:2014-10-16 09:10:53

标签: c# datagridview

我有一个datagridview,我正在尝试添加一个新行。 它有3列,0 =图像,1 =文本,2 =文本。

它将第一行添加为罚款,但是当我再次单击以添加第二行时,它会抛出异常。

        DataGridViewRow row = new DataGridViewRow();
        dataGridView.Rows.Add(row);
        row.Cells[1].Value = message; //specified argument was out of the range of valid values.
        row.Cells[2].Value = response;

2 个答案:

答案 0 :(得分:0)

您必须将添加到DataGridViewRow

  ...
  // At least 3 columns required: Cells[] is a zero based collection
  row.Cells.Add(new DataGridViewTextBoxCell()); // <- Ckeck cell actual type
  row.Cells.Add(new DataGridViewTextBoxCell()); // <- Ckeck cell actual type
  row.Cells.Add(new DataGridViewTextBoxCell()); // <- Ckeck cell actual type

  row.Cells[1].Value = message; // OK
  row.Cells[2].Value = response;

从现有dataGridView开始的更好方法:

  DataGridViewRow row = dataGridView.Rows[dataGridView.Rows.Add()];

  row.Cells[1].Value = message; 
  row.Cells[2].Value = response;

答案 1 :(得分:0)

//试试这个: dataGridView.Rows.Add(NULL,消息,响应)