如何强制用户在数据库字段中输入值

kom*_*mbo 1 c# sql-server window

使用我的应用程序,我想确保用户是否在文本框中没有输入值,然后单击
保存按钮以在sqlserver db中发送数据.数据库端验证可防止此违规并设置我的应用程序将捕获的ErrorMessage并显示
向用户传达含义的消息.对于每个必填字段,我将其设置为NOT NULL.但是当我测试时,我仍然可以输入
输入的空文本框值,它会插入带有值的值.我错过了什么?

string connectionstring = "Data Source=abcdef;Initial Catalog=HMS;Persist Security Info=True;User ID=sysad;Password=abcdef";
        SqlConnection connection = new SqlConnection(connectionstring);

        string SelectStatement = "SELECT * FROM tablename where RegistrationNo = @RegistrationNo";
        SqlCommand insertcommand = new SqlCommand(SelectStatement, connection);
        insertcommand.Parameters.AddWithValue("@RegistrationNo", textBox10.Text);
        SqlDataReader reader;
        try
        {
            connection.Open();
            reader = insertcommand.ExecuteReader();

            while (reader.Read())
            {
                textBox11.Text = reader["RegistrationNo"].ToString();
                textBox1.Text = reader["Appearance"].ToString();
                textBox2.Text = reader["VolumePH"].ToString();
                textBox3.Text = reader["Mobility"].ToString();
                textBox4.Text = reader["Viability"].ToString();
                textBox5.Text = reader["Head"].ToString();
                textBox6.Text = reader["MiddlePiece"].ToString();
                textBox7.Text = reader["Tail"].ToString();
                textBox8.Text = reader["SpermCount"].ToString();
                dateTimePicker1.Text = reader["Date"].ToString();
                textBox9.Text = reader["Comment"].ToString();



            }//end while
            reader.Close();
        }
        catch (Exception ex)
        {
            throw ex;

        }//end catch
Run Code Online (Sandbox Code Playgroud)

das*_*ght 7

我错过了什么?

我认为你错过了null一个空字符串的区别.

数据库区分nullempty.如果ToString成功,那么你有一个非空字符串,因此DB很乐意接受它作为有效值.

通常,使用DB进行用户端验证有点浪费:如果您知道该字段不能为空,则应在UI中检查它; 数据库验证应作为保留数据模型完整性的最后手段.