如何防止用户保存具有空值的记录?

时间:2022-11-11 23:39:30

I'm very new to database programming and I've got 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?

我是数据库编程的新手,我有一个小型数据库(SQL CE 3.5)。它有一个“LastName”列,不接受空值。我正在使用BindingNavigator来解决问题。我是否必须为该导航器上的每个控件设置类似于下面的事件。或者有更简单的方法吗?

I'm using C# with .NET 3.5 and WinForms. This is also just a single table db.

我正在使用C#与.NET 3.5和WinForms。这也只是一个表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

2 个解决方案

#1


1  

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

第一个是你的SQL代码。你可以使用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?

那对你有用吗?

#2


2  

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?

另外,为什么不使用RequiredFieldValidator来确保在该字段中没有值的情况下无法回发表单?

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx

#1


1  

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

第一个是你的SQL代码。你可以使用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?

那对你有用吗?

#2


2  

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?

另外,为什么不使用RequiredFieldValidator来确保在该字段中没有值的情况下无法回发表单?

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx