Reputation: 19
I am trying to get data out of 2 cells on the last line of DataGridView in C#. These lines of code give me Index was out of range. Must be non-negative and less than the size of the collection.
intNumberOfRows = dgvWellsFargo.RowCount;
txtNoOfTransactions.Text = dgvWellsFargo.Rows[intNumberOfRows].Cells[1].Value.ToString();
txtTotal.Text = String.Format("{0:c2}", dgvWellsFargo.Rows[intNumberOfRows].Cells[2].Value.ToString());
As you can see I am trying to use the RowCount for my index which I assume is what I need to use. Is there another parameter that I should be using?
I appreciate any suggestions.
Upvotes: 0
Views: 103
Reputation: 5453
You should use :
intNumberOfRows = dgvWellsFargo.RowCount - 1;
The reason is, if you have 5 rows in your gridview, then the count will be 5 and if you know, row index starts with 0. So dgvWellsFargo.Rows[intNumberOfRows]
means dgvWellsFargo.Rows[5]
, but you have max row index 4
Also, you have 2 cells, so the cell index should be used Cells[0] and Cells[1]
So your final code should be :
int lastRowIndex = dgvWellsFargo.RowCount - 1;
txtNoOfTransactions.Text = dgvWellsFargo.Rows[lastRowIndex].Cells[0].Value.ToString();
txtTotal.Text = String.Format("{0:c2}", dgvWellsFargo.Rows[lastRowIndex].Cells[1].Value.ToString());
Upvotes: 3