0

I've been trying to add a DataGridViewRow to a DataGridView to no avail. I followed the answers here. I can't for the life of me figure out what is wrong with my code!

I'd like to add data using associative keys and not indices :

row.Cells["Column2"].Value = "XYZ";
row.Cells["Column6"].Value = 50.2;

This is my code:

DataGridViewRow dgvr = (dgvSponsor.RowTemplate);
        dgvr.Cells["firstName"].Value = fn;
        dgvr.Cells["midName"].Value = mi;
        dgvr.Cells["lastName"].Value = ln;
        dgvr.Cells["suffix"].Value = suffix;
        dgvr.Cells["residence"].Value = res;
        dgvr.Cells["gender"].Value = radioMale.Checked ? 1 : 2;

I'm getting an ArgumentException: enter image description here

I've already set the names for the columns like so: enter image description here

Why is it still throwing an Exception?

Donovan Keating
  • 1,715
  • 3
  • 17
  • 27

2 Answers2

1

There are different ways to add data, but the way I mostly use is to create the row and then add the data as follows;

//Insert a new row, get the index of that row
int index =  myDataGridView.Rows.Add();

//Now add the data into the row you just created
myDataGridView.Rows[index].Cells["firstName"].Value = fn;
myDataGridView.Rows[index].Cells["midName"].Value = mi;
myDataGridView.Rows[index].Cells["lastName"].Value = ln;
myDataGridView.Rows[index].Cells["suffix"].Value = suffix;
myDataGridView.Rows[index].Cells["residence"].Value = res;
myDataGridView.Rows[index].Cells["gender"].Value = radioMale.Checked ? 1 : 2;
jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
0

enter image description here

Try set DataPropertyName to firstName and all other columns in a row should be set accordingly.

muhammad hasnain
  • 501
  • 4
  • 16