Hi there,
I have a question regarding datagridview, I add data to the datagridview in an interface and all the validation for the datagridview cell is in the datagridview cell validating event for the datagridview. I display the data of the is datagridview in another interface and make the cells read-only. And the newly added rows can be editable. But the thing is when I click on a row that data was added previously and press the Add new row the cell validating event is triggered. How can I disable the cell validating event for the rows that was added before???


thankxxxxxx

There are two ways to manage unwanted execution of event handlers.

1) Add a conditional statement in the event handler code to only execute when required.
2) Detach the event hander before the unwanted event triggers and re-attach after.

There are two ways to manage unwanted execution of event handlers.

1) Add a conditional statement in the event handler code to only execute when required.
2) Detach the event hander before the unwanted event triggers and re-attach after.

hey can you give me alink or a sample code for me to do the above two????

1)
if (conditional)
{
// do your thing
}

2)
DGV.eventname -= new eventnameHandler(YourMethod);
// do your thing
DGV.eventname += new eventnameHandler(YourMethod);

hey can you give me alink or a sample code for me to do the above two????

how do i call the call_validating event in a function in C# according to your second option

thanx

1)
if (conditional)
{
// do your thing
}

2)
DGV.eventname -= new eventnameHandler(YourMethod);
// do your thing
DGV.eventname += new eventnameHandler(YourMethod);

hey why is this line of code wrong???????
dgvSubContractor.CellValidating -= new DataGridViewCellValidatingEventArgs(dgvSubContractor_CellValidating);

it says that "Error 7 'System.Windows.Forms.DataGridViewCellValidatingEventArgs' does not contain a constructor that takes '1' arguments"

what is the solution for this???????

It should be DataGridViewCellValidatingEventHandler

hey i used it it dosen't work,

my cell validating evet is as below

/// <summary>
        /// This event handler is called when user has finished editing/viewing the current cell
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>           
        private void dgvSubContractor_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            DataGridViewComboBoxCell cell = dgvSubContractor.CurrentCell as DataGridViewComboBoxCell;

            if (cell != null && !cell.Items.Contains(e.FormattedValue))
            {
                // Insert the new value into position 0
                // in the item collection of the cell
                cell.Items.Insert(0, e.FormattedValue);
                // When setting the Value of the cell, the  
                // string is not shown until it has been
                // comitted. The code below will make sure 
                // it is committed directly.
                if (dgvSubContractor.IsCurrentCellDirty)
                {
                    // Ensure the inserted value will 
                    // be shown directly.
                    // First tell the DataGridView to commit 
                    // itself using the Commit context...
                    dgvSubContractor.CommitEdit(DataGridViewDataErrorContexts.Commit);
                }
                // ...then set the Value that needs 
                // to be committed in order to be displayed directly.
                cell.Value = cell.Items[0];
            }

            String headerText = dgvSubContractor.Columns[e.ColumnIndex].HeaderText;
            if (headerText.Equals("Email"))
            {
                if (!string.IsNullOrEmpty(e.FormattedValue.ToString()))
                {
                    if (c.isEmail(e.FormattedValue.ToString()))
                    {
                        if (c.ValidateDBEmail(e.FormattedValue.ToString()))
                        {
 [B]                           MessageBox.Show("Enter unique email that is not in the DB");[/B]
                            e.Cancel = true;

                            ////TODO::add the code for setting the cursor in the datagridview email cell
                            //dgvSubContractor.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
                            //MessageBox.Show(e.ColumnIndex.ToString());
                            //dgvSubContractor.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = null;

                            //dgvSubContractor.CurrentCell = dgvSubContractor.Rows[e.RowIndex].Cells[2];
                            //dgvSubContractor.BeginEdit(true);
                        }
                        //else
                        //    MessageBox.Show("Valid email address");
                    }
                    else
                    {
                        MessageBox.Show("email address format invalid");
                        e.Cancel = true;
                    }
                }
            }

            if (headerText.Equals("Telephone No"))
            {
                if (!string.IsNullOrEmpty(e.FormattedValue.ToString()))
                {
                    if (!c.ValidateTelNo(e.FormattedValue.ToString()))
                    {
                        MessageBox.Show("Phone Number Must Be Entered As: (555) 555-1234");
                        e.Cancel = true;
                    }
                }
            }
        }

the line bolded execute everytime i add a new row and does not allow me to add a row to the datagrid view???

I think that the DGV is probably executing this event because of some other update you are doing in your code.

Try using method 1 like this:

// flag to block CellValidating event while adding row
bool addingRow = false; 

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (addingRow)
        return;
    // validate other stuff
}

void RowAddMethod()
{
    addingRow = true;
    // Do all add row related actions
    addingRow = false;
}

I think that the DGV is probably executing this event because of some other update you are doing in your code.

Try using method 1 like this:

// flag to block CellValidating event while adding row
bool addingRow = false; 

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (addingRow)
        return;
    // validate other stuff
}

void RowAddMethod()
{
    addingRow = true;
    // Do all add row related actions
    addingRow = false;
}

hey
what do ouy mena by the below


private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (addingRow)
return;
// validate other stuff
}

if (addingRow) - is to call the button event for adding a new row is it

If I have it right, you do not want the event code to execute while you do your row add.
The addingRow flag is set true before you add your row and cleared to false after all your updates are complete.
If the DGV executes the CellValidating event while you are adding the new row,
the if (addingRow) return; will cause the event handler code exit without doing anything.

If I have it right, you do not want the event code to execute while you do your row add.
The addingRow flag is set true before you add your row and cleared to false after all your updates are complete.
If the DGV executes the CellValidating event while you are adding the new row,
the if (addingRow) return; will cause the event handler code exit without doing anything.

yeah but how do i do it????
what should i add to the if condition??? to the addingRow

I think that the DGV is probably executing this event because of some other update you are doing in your code.

Try using method 1 like this:

// flag to block CellValidating event while adding row
bool addingRow = false; 

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (addingRow)
        return;
    // validate other stuff
}

void RowAddMethod()
{
    addingRow = true;
    // Do all add row related actions
    addingRow = false;
}

hey but before the add row method the cell validating event is trggered,
don't know why is that???

I don't know.
Did you try using Debug?
If you step through your add row code you should find out what is triggering the event.

I don't know.
Did you try using Debug?
If you step through your add row code you should find out what is triggering the event.

every time the cell validating event triggers and a value is entered in the datagridview cell right??

so when i click the add button the cell validating event triggers

i have posted the cell validating event do you know how to solve this

thanxxx

The problem is most likely in your add button code!!!
Something there is causing the cell validating event to fire.
Look there for you answer.
[Edit]
The validating event is firing because focus is being moved from the DGV to the button.
Since you have not added your new row yet it should validate OK.
Or if not, then it is because the user has entered an invalid value in the current cell.

Edited 6 Years Ago by nick.crane: n/a

Comments
focus change is the culprit :)

The problem is most likely in your add button code!!!
Something there is causing the cell validating event to fire.
Look there for you answer.
[Edit]
The validating event is firing because focus is being moved from the DGV to the button.
Since you have not added your new row yet it should validate OK.
Or if not, then it is because the user has entered an invalid value in the current cell.

hey
the add button for the datagridview is below

if (tabControl.SelectedIndex == 4)
            {
                dgvCAddR = dgvComm.Rows.Count;

                if (dgvCAddR == 0)
                {
                    dgvComm.Rows.Add();
                    dgvCAddR++;
                }
                else if ((dgvComm.Rows[dgvCAddR - 1].Cells[0].Value != null) && (dgvComm.Rows[dgvCAddR - 1].Cells[1].Value != null))
                {
                    dgvComm.Rows.Add();
                    dgvCAddR++;
                }
                else
                    MessageBox.Show("Enter details to the previous row");
            }

but this dosen't trigger the cell validating event???

The problem is most likely in your add button code!!!
Something there is causing the cell validating event to fire.
Look there for you answer.
[Edit]
The validating event is firing because focus is being moved from the DGV to the button.
Since you have not added your new row yet it should validate OK.
Or if not, then it is because the user has entered an invalid value in the current cell.

"The validating event is firing because focus is being moved from the DGV to the button.
Since you have not added your new row yet it should validate OK."

yeah i think it is because of the line you have said above

how can i avoid this situation???

thanxxxxxxxxxxx

If you have attached an event handler to the CellValidating event then it will always fire when focus leaves the cell.
If there are cells that you dont want to validate (eg read only cells) then add a check at the start of the event handler that will cause it to exit if it is trying to validate those cells.

For instance, if column with index 2 is read only and you dont want to validate cells in that column you could use:

private void dgvSubContractor_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if(e.ColumnIndex == 2)
        return;

    //do validation here
}

If the user focuses on a cell in column 2 then clicks on the button, the event handler will fire but will return before executing the validation code.

If you have attached an event handler to the CellValidating event then it will always fire when focus leaves the cell.
If there are cells that you dont want to validate (eg read only cells) then add a check at the start of the event handler that will cause it to exit if it is trying to validate those cells.

For instance, if column with index 2 is read only and you dont want to validate cells in that column you could use:

private void dgvSubContractor_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if(e.ColumnIndex == 2)
        return;

    //do validation here
}

If the user focuses on a cell in column 2 then clicks on the button, the event handler will fire but will return before executing the validation code.

my methods in the cell validating event are as below

if (headerText.Equals("Telephone No"))
                {
                    if (!string.IsNullOrEmpty(e.FormattedValue.ToString()))
                    {
                        if (!c.ValidateTelNo(e.FormattedValue.ToString()))
                        {
                            MessageBox.Show("Phone Number Must Be Entered As: (555) 555-1234");
                            e.Cancel = true;
                        }
                    }
                }

do i have to put the if(e.ColumnIndex == 2) ???

No. I was giving you an example.
My code showed you how to skip the validation for column 2. You need to change it so that it skips the validation for columns or rows you don't want to validate.

This article has been dead for over six months. Start a new discussion instead.