Michael O'Dea-Jones' Blog

BindingNavigator + Validation = Grief

I received a rather nasty shock to discover that you can't use the BindingNavigator Validating event to stop navigating to the next, previous, first or last record in a DataSource if there are validation errors on your Form. If you are using a DataGridView then set e.Cancel to true in the DataGridView's RowValidating event:

private void form1Form_Load(object sender, EventArgs e)

{

this.jobTableAdapter.Fill(this.hermesDataSet.Job);

form1DataSet.Job.ColumnChanging += new DataColumnChangeEventHandler(Job_ColumnChanging);

jobDataGridView.RowValidating += new DataGridViewCellCancelEventHandler(jobDataGridView_RowValidating);

}

void Job_ColumnChanging(object sender, DataColumnChangeEventArgs e)

{

if (e.Column.ColumnName == "JobItem")

{

if (string.IsNullOrEmpty(e.ProposedValue.ToString()))

{

e.Row.SetColumnError(e.Column.ColumnName, "Item cannot be empty");

}

else

{

e.Row.SetColumnError(e.Column.ColumnName, string.Empty);

}

}

}

void jobDataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e)

{

if (hermesDataSet.Job.HasErrors)

{

e.Cancel = true;

}

}

If you are aren't using a DataGridView then set e.Cancel to true in the Control's (e.g. TextBox ) Validating event:

private void taskStateNameTextBox_Validating(object sender, CancelEventArgs e)

{

if (string.IsNullOrEmpty(taskStateNameTextBox.Text))

{

taskStateErrorProvider.SetError(taskStateNameTextBox, "Name cannot be empty");

e.Cancel = true;

}

else

{

taskStateErrorProvider.SetError(taskStateNameTextBox, string.Empty);

}

}

Published Sunday, August 10, 2008 3:54 PM by michael@wardyit.com

Comments

No Comments
Anonymous comments are disabled

News

Michael is a .Net Developer who enjoys creating software and doing database work too.

Tags

No tags have been created or used yet.