Reputation: 1473
Firstly I'm quite new with programming(first week). I have a datagridviewer and CellClick event on it. What my function do is, gets the first column value of selected(mouse left clicked) cell of row. Like;
ID Name Address ( this ones Headers of gridview)
1 User1 Address1
2 User2 Address2
..6,7..
9 User9 Address9
When you click on any cell -except Headers- it gives the value of first column. When you click, Address9 your value will return as 9 etc.
I get outofexception error when header cell is clicked. Which returns -1 value and crashs.So, I need a if statement to ignore header clicks. I searched it on websites and tried many things myself but haven't managed to achieve this.
private void dgwCust_CellClick(object sender, DataGridViewCellEventArgs e)
{
if ( cellclick == isn't a header click?.. )
string search;
search = dgwCust.Rows[e.RowIndex].Cells[0].Value.ToString();//this is where error comes in
SqlCommand cmdsearch = new SqlCommand("Select * from Customers where CustomerID = '" + search + "'", dbConnection);
try
{
etc..
Upvotes: 1
Views: 1576
Reputation: 6562
Check if e.RowIndex does not equal -1 by using one of the following
if (!e.RowIndex.Equals(-1))
or
if (e.RowIndex != -1)
-
private void dgwCust_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (!e.RowIndex.Equals(-1))
string search;
search = dgwCust.Rows[e.RowIndex].Cells[0].Value.ToString();//this is where error comes in
SqlCommand cmdsearch = new SqlCommand("Select * from Customers where CustomerID = '" + search + "'", dbConnection);
try
{
Upvotes: 2
Reputation: 1
if (e.RowIndex >= 0)
{
string search;
search = dgwCust.Rows[e.RowIndex].Cells[0].Value.ToString();//this is where error comes in
SqlCommand cmdsearch = new SqlCommand("Select * from Customers where CustomerID = '" + search + "'", dbConnection);
//...
}
Upvotes: 0