views:

73

answers:

2

I wish to prevent the user from saving changes made to a DataGridView if it has any validation errors (set using the ErrorText property of a cell using the CellValidating event).

I'm looking for (but cannot see) a method such as myDataGridView.HasErrors()?

A: 

Hi in msdn there is an example on how to validate the DataGridView have a look...

DataGridView

i hope it helped

arik
Sorry, maybe I wasn't clear in the original question. I am already validating the cells fine, and setting the ErrorText wherever appropriate. I just want to know if any cells have failed validation so that I can prevent the user from clicking a "Save" button.
Rezzie
A: 

Just do it at the same time you are validating the rows. Using the MSDN example arik posted...

private void dataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
{
    dataGridView1.Rows[e.RowIndex].ErrorText = "";
    int newInteger;

    if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
    if (!int.TryParse(e.FormattedValue.ToString(),
        out newInteger) || newInteger < 0)
    {
        e.Cancel = true;
        dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a non-negative integer";

        //If it's simple, do something like this here.
        this.SubmitButton.Enabled = false;

        //If not, set a private boolean variable scoped to your class that you can use elsewhere.
        this.PassedValidation = false;
    }
}
Ocelot20
This doesn't cope with multiple columns though, does it? For example, say the first cell fails validation - the submit button is disabled. Then the next cell passes validation - the submit button will be enabled, even though a previous cell failed...?
Rezzie
Why would the submit button re-enable itself without being explicitly directed to do so? The code above isn't meant to be the exact code you use. It was meant to illustrate a point (that you can invalidate whatever you want as failure occurs).
Ocelot20
Rezzie
Without seeing your code and what you're trying to accomplish, my only answer can be...wherever it makes sense to do so. I mean, if there was such a .HasErrors method, where would you call it from?
Ocelot20
In the CellValidation event? `this.SubmitButton.Enabled = !dataGridView1.HasErrors()`
Rezzie
The DataGridView does not implement an HasErrors method, much to the OP's dismay.
Kharlos Dominguez