• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

DataGridView Question (C#)

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
Here is what I am trying to do;
When a user enters data into a DataGridView cell (TextBox) and then hits tab to advance to the next column, I want to verify the data and respond appropriately.

Overriding the CellEndEdit event I can easily validate the data.
The problem that I am seeing is that if the data is invalid, I want to return the users to the cell with the invalid data and set it back in edit mode.
I can't seem to get this to work the way I am trying, and can't seem to find anything.

The following code simply check to see if that a valid work order number was entered by
seeing if an ExecuteScalar call returns anything.

Code:
private void laborDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            object temp;
            // Check for Valid WO #
            if (e.ColumnIndex == 3)
            {
                SqlCommand sqlCom = new SqlCommand(
                    "select WOListID from WorkOrders where WONum='" +
                    laborDataGridView[e.ColumnIndex, e.RowIndex].Value.ToString().Trim() + "' " +
                    "and Completed='false'", sqlCon);
                sqlCon.Open();
                temp = sqlCom.ExecuteScalar();
                if (temp == null)
                {
                    MessageBox.Show("WO # " +
                        laborDataGridView[e.ColumnIndex, e.RowIndex].Value.ToString().Trim() +
                        " is either completed or does not exist", "Data Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    laborDataGridView[e.ColumnIndex, e.RowIndex].Value = "";
// The next line does not return the user to the cell with invalid data
                    laborDataGridView[e.ColumnIndex, e.RowIndex].Selected = true;
                    sqlCon.Close();
                    return;
                }
                sqlCon.Close();
            }
// rest of code removed. .........

The value of the offending cell is set to null (""), but the next column's cell gets the focus and selection.
Any ideas ?
 
Top