1

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..

2
  • 1
    Metro? WinForms? WPF? Silverlight? Windows Phone? ASP.Net? MonoTouch? Commented Dec 10, 2013 at 18:27
  • WinForms, but problem is already solved. Thanks. Commented Dec 10, 2013 at 18:45

2 Answers 2

2

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
        { 
Sign up to request clarification or add additional context in comments.

Comments

0
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);
  //...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.