views:

331

answers:

3

I have a datagridview that I would like to validate using the cellvalidating event. however as the user doesnt navigate between cells or rows in the datagridview. just enters data in a cell in the datagridview and then clicks a save button the cellvalidating event doesnt get fired. any help would be greatly appreciated.

A: 

It is obviously in the Win Forms environment.

Here is the answer to the problem.

I am accepting a datatable as my datasource for the gridview

        DataTable dtSource = new DataTable();
        #region Data Table Creation

        dtSource.Columns.Add("NumericColumn1");
        dtSource.Columns.Add("NumericColumn2");
        dtSource.Columns.Add("NumericColumn3");


        #endregion

        #region Add Rows
        dtSource.Rows.Add("1", "2", "3");
        dtSource.Rows.Add("4", "5", "6");
        dtSource.Rows.Add("7", "8", "9");

        #endregion

        dataGridView1.DataSource = dtSource;

My objective is to check if a user has entered anything in any of the cell apart from a numeric value, then upon clicking on the SAVE button an error message should be populated.

In the cell validating event , I have written the following

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

        if (!(IsNumeric(e.FormattedValue.ToString(), System.Globalization.NumberStyles.Integer)))
        {
            flag = !flag;
            dataGridView1.Rows[e.RowIndex].ErrorText = "Only numeric values are accepted";
        }
        else
        {
            flag = true;
        }
}

The IsNumeric function is as under

public bool IsNumeric(string Val, System.Globalization.NumberStyles NumberStyle)
{
    Double result;

    return Double.TryParse(Val, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
}

And in the SAVE button event , I am checking the status of the validation

private void SAVE_Click(object sender, EventArgs e)
{
    if (flag == true)           
    {
        MessageBox.Show("Every thing is ok");
    }
}

Hope this helps

priyanka.sarkar
the problem is that the cell validating event doesnt get called.I have ended the edit on both datagridview and the bindingsourceMe.Tbl_LookUpValuesDataGridView.EndEdit()Me.Tbl_LookUpValuesBindingSource.EndEdit()
sean
+1  A: 

Before you save data, you can call ValidateChildren on the form to force all controls to validate themselves. the method will return false if there was a validation error. You use it like this:

Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
    If Me.ValidateChildren Then
       ...Save
    End If
End Sub
Meta-Knight
A: 
private void dgv_CellLeave(object sender, DataGridViewCellEventArgs e)
{

    if (e.RowIndex > -1)
    {
     if (dgv[e.ColumnIndex, e.RowIndex].IsInEditMode)
     {
      dgv.EndEdit();
     }
    }
}
Vivek