How can I prevent a user from saving a record with a null value?
I'm very new to database programming and I've 开发者_如何学JAVAgot a small database (SQL CE 3.5). It has a "LastName" column that doesn't accept nulls. I'm using the BindingNavigator to get around. Do I have to set an event similar to below for every control on that navigator. Or is there an easier way around it?
I'm using C# with .NET 3.5 and WinForms. This is also just a single table db.
if (!string.IsNullOrEmpty(lastNameTextBox.Text))
{
this.Validate();
this.tblMembersBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.dataSet1);
}
else
{
MessageBox.Show("The Last Name Field cannot be empty");
}
Thanks
You should really be using:
if (!string.IsNullOrEmpty(lastNameTextBox.Text))
{
...
}
Also, why not just use the RequiredFieldValidator to ensure that the form can't be posted back without a value in that field?
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx
There are a couple ways you could do it.
The first would be in your SQL code. You could use
isnull(lastname, 'something')
- http://msdn.microsoft.com/en-us/library/ms184325.aspx
Or you could give the column a default value in the database -
ALTER TABLE your_table_name ADD CONSTRAINT
Name_of_Constraint DEFAULT 'value' FOR column_name
That work for you?
精彩评论