I have some serious problem with DataGridView input validation:
I'm working on a project with Entity Framework and I've bound a DataGridView element to a database.
If the user inserts some data into a non-nullable column, and after that clears the data to leave the column blank, then clicks on another DataGridView cell, an exception occurs and I get a run-time error.
Alternately, if a user tries to insert a string into an integer column, they get a very long error message which isn't user friendly at all.
Is it any easy way to validate DataGridView cells?
I believe you are looking for DataGridView.DataError
event. you should handle this event if you want to have custom validation on data. something like this:
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = entities;
dataGridView1.DataError += new DataGridViewDataErrorEventHandler(dataGridView1_DataError);
}
void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
// you can obtain current editing value like this:
string value = null;
var ctl = dataGridView1.EditingControl as DataGridViewTextBoxEditingControl;
if (ctl != null)
value = ctl.Text;
// you can obtain the current commited value
object current = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
string message;
switch (e.ColumnIndex)
{
case 0:
// bound to integer field
message = "the value should be a number";
break;
case 1:
// bound to date time field
message = "the value should be in date time format yyyy/MM/dd hh:mm:ss";
break;
// other columns
default:
message = "Invalid data";
break;
}
MessageBox.Show(message);
}
you can check the value of entered data and show appropriate error message for that value. for example if value is null or empty and the field is not nullable, you can show a message indicating that the value cannot be empty.
Hope this helps.