Click here to Skip to main content
15,911,132 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm not understand why I'm "periodically" get an Index out of range exception. I can't reproduce but here's the code:

</code>
private void Form1_Load(object sender, EventArgs e)
{
DataGridViewButtonColumn btnShow = new DataGridViewButtonColumn();
dgvDisplay.Columns.Add(btnShow);
btnShow.HeaderText = "Show";
btnShow.Name = "btnShow";
btnShow.Text = "SHOW";
btnShow.UseColumnTextForButtonValue = true;

dgvDisplay.Columns.Add("ID", "Id");
dgvDisplay.Columns.Add("PERSON", "Person");

dgvDisplay.Rows.Add("","123", "John Doe");
dgvDisplay.Rows.Add("","456", "Jane Doe");
}

private void dgvDisplay_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
string s = (string)dgvDisplay.Rows[e.RowIndex].Cells[1].Value;
MessageBox.Show(s);
}
}
<code>

So basically when I click the button I'm retrieving the ID result and displaying it a MsgBox. But periodically I throw an Index out of Range exception.
Posted
Comments
Dinesh Mani 2-Mar-12 0:45am    
I assume you are getting the error when you access the e.RowIndex property? Are you able to pinpoint when this error occurs? May be it only occurs when clicking on the row header?

If you are not able to pin point / reproduce the error I would suggest you mask it by having a try...catch block around the code and doing nothing on the index out of range exception.

BTW, When you have buttons on the gridview to initiate this, why not use command click event rather than the cell click event?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900