DataGridView in TabControl and CellValidating lead to problems.

  • Thread starter Thread starter AlbuEmil
  • Start date Start date
A

AlbuEmil

Guest
I created a little form with a TabControl on it and a combobox.

On the first page i added a DataGridView with 2 columns, not bound to any data (data entered directly).

Also, for the grid i added an event handler for CellValidating in which i test if the data from the first row is numeric, if not i show a message box with an error and return e.Cancel = true so the DataGridView maintains focus.

Now, if i do the following :

1 - edit cell on first column and enter a wrong value (a text)

2 - click on TabControl to change to the other tab page, error is shown that the value is not correct, close the error

3 - modify the value to be correct (enter a number)

4 - change to any of the other cells in the DataGridView and try to edit them with the mouse (double click to edit), it just doesnt work.

The only solution to "fix" this is to change to the other tabPage on the TabControl and back, this way the DataGridView regains its ability to edit cells with the mouse.

Is there any solution to this ?

Note: If i dont show the message box in the CellValidating function then the problem doesnt occur. I know i could show an errormessage on the row of the column, but the application im writing requires that i display messageboxes for all errors (and i cant make the grid work differently from all other controls on the other dialogs just because of this bug).

So, is there any way to fix this ?



Heres my code (at least the part that relates to the problem)

public Form1()
{
InitializeComponent();

// add some data to the grid so its not empty

// first row
DataGridViewRow row = new DataGridViewRow();
DataGridViewTextBoxCell value = new DataGridViewTextBoxCell();
DataGridViewTextBoxCell text = new DataGridViewTextBoxCell();
value.Value = "12";
text.Value = "some text";

row.Cells.Add(value);
row.Cells.Add(text);

dataGridView1.Rows.Add(row);

// second row
row = new DataGridViewRow();
value = new DataGridViewTextBoxCell();
text = new DataGridViewTextBoxCell();
value.Value = "1000";
text.Value = "another text";

row.Cells.Add(value);
row.Cells.Add(text);

dataGridView1.Rows.Add(row);
}

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
// first row must be numeric value
if (e.ColumnIndex == 0)
{
try
{
double x = Convert.ToDouble(e.FormattedValue);
}
catch (System.Exception ex)
{
MessageBox.Show("Error, value is not a double");
// if we cant convert then bail out
e.Cancel = true;
}
}
}

...
private void InitializeComponent()
{
...
this.dataGridView1.CellValidating += new System.Windows.Forms.DataGridViewCellValidatingEventHandler(this.dataGridView1_CellValidating);
...
}


Continue reading...
 
Back
Top