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

时间:2012-06-26 12:27:53

标签: c# sql-server window

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

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

4 个答案:

答案 0 :(得分:7)

  

我缺少什么?

我认为你错过了null和空字符串之间的区别。

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

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

答案 1 :(得分:1)

您可以在服务器端代码中使用requiredfield验证器并进行验证。如果是空字符串则返回错误本身。

转到sql server并抛出错误很糟糕。

if(txtBox.Text.Trim() == string.Empty)
  //throw "cannot be null error to user;

答案 2 :(得分:0)

当按下按钮时,检查字段可能是个好主意。例如:

private void button_Click(object sender, EventArg e){
   if (textbox1.Text == ""){
      MessageBox.Show("Your message to the user");
   }
}

希望有所帮助

答案 3 :(得分:0)

最好检查用户界面中的用户输入。如果用户必须输入一些值,则应在尝试将其插入数据库之前进行检查。