I have a DataGridView with several columns, including buttons and combo boxes. I am trying to implement a validation that triggers when the DataGridView loses focus and this works as expected. However, the same validation is also triggered when moving from a Text column to a non-Text (button, combo box) column within the DataGridView.
Does anyone have any suggestions on how to resolve this? I have tried various possible solutions but have not been able to completely resolve the issue.
Here is what my code for the event handler and the event handler initializer look like:
Initializer:
dgvCopy.LostFocus += dgvCopy_LostFocus;
Event Handler:
private void dgvCopy_LostFocus(object sender, EventArgs e) {
if (dgvCopy.SelectedRows.Count > 0) {
if (dgvCopy.SelectedRows[0].Cells["Type"].Value == null) {
MessageBox.Show("Please choose a type");
txtCopyText.Enabled = false;
}
else {
txtCopyText.Enabled = true;
}
}
Any help or advice is much appreciated!
You can use Validating
event instead of LostFocus
.
LostFocus
fires also when the editing control of a cell shows but Validating
only fires when the DataGridView
is not active control of the form anymore or when you call ValidateChildren
on the Form
.
void dataGridView1_Validating(object sender, CancelEventArgs e)
{
//Perform Validation Here
}
Pay attention that when you leave the DataGridView
the Validating
fires only if the CausesValidation
property of the new active control is set to true.
So based on your requirement, you may want to use Leave
event instead.
When you nest your controls, you should set the CausesValidation
property on each nested control to false, then use the Validating
event over the LostFocus
event to verify data, then the Validated
event to continue flow on success. If you want to have focus changes fire non-validation events, and you want it to update through a hierarchy of nesting, you should consider using Leave
instead of LostFocus
, as LostFocus is very close to the metal and leave handles contained controls.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.