Reputation: 6440
In our application, we are adding a row to a datatable. I would like to validate the row before it is added to the table, and if the data doesn't meet business requirements, the row does not get added. I would think RowChanging even is where I need to add validation code. However, how do I prevent the row from being added to the DataTable?
Upvotes: 1
Views: 1533
Reputation: 9
Suppose We Have a DataGridView. You must use dataGridView1_RowValidating Event. A smple code is below:
private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e) {
if (dataGridView1.IsCurrentRowDirty==true)
{
if (dataGridView1.Rows[e.RowIndex].Cells["FirstName"].Value.ToString() == "")
e.Cancel = true;
MessageBox.Show("Please enter Student FirstName");
}
}
Upvotes: 0
Reputation: 53593
I think the only way you can stop a row from being added in the RowChanging
event handler is to throw an Exception:
if (e.Action == DataRowAction.Add) {
if (e.Row["SomeColumn"].ToString() == "AnInvalidValue") {
throw new InvalidOperationException("You can't do that.");
}
}
You'd obviously have to catch this exception and handle it gracefully.
A better approach would be to do your validation in the UI before attempting to add the new DataRow
.
Upvotes: 2