简体   繁体   English

空文本框仍然在SQL Server中保存数据,即使表中的列也不允许为null

[英]Empty Textbox still saves data in SQL Server even columns in table are not allowed null

I am facing this issue, when I click save button when all textboxes are empty it shows stars labels on all of them. 我正面临这个问题,当我在所有文本框都为空时单击“保存”按钮时,它会在所有文本框上显示星标。 When I fill last textbox leaving all others empty, it saves data into database with empty strings. 当我填写最后一个文本框而其他所有文本框都为空时,它会将数据保存到空字符串数据库中

How can I handle this issue? 我该如何处理这个问题?

if (tbIDCardNum.Text.Trim() == "")
{
    lblStarIDCardNum.Visibility = Visibility.Visible;
}

if (tbFirstName.Text.Trim() == "")
{
    lblStarFirstName.Visibility = Visibility.Visible;
}

if (rbMale.IsChecked == false && rbFemale.IsChecked == false)
{
    lblStarGender.Visibility = Visibility.Visible;
}

if (tbDOB.Text == "")
{
    lblStarDOB.Visibility = Visibility.Visible;
}

if (tbDateOfJoining.Text == "")
{
    lblStarDOJ.Visibility = Visibility.Visible;
}

if (tbEducation.Text.Trim() == "")
{
    lblStarEducation.Visibility = Visibility.Visible;
}

if (tbCNIC.Text.Trim() == "")
{
    lblStarCNIC.Visibility = Visibility.Visible;
}

if (tbSalary.Text.Trim() == "")
{
    lblStarSalary.Visibility = Visibility.Visible;
}

if (tbAddress.Text.Trim() == "")
{
    lblStarAddress.Visibility = Visibility.Visible;
}

if (tbEmail.Text.Trim() == "")
{
    lblStarEmail.Visibility = Visibility.Visible;
}

if (tbContact1.Text.Trim() == "")
{
    lblStarContact.Visibility = Visibility.Visible;
}
else
{
    try
    {
        conn.Open();

        cmd.CommandText = "insert into teacher (tIDCardNum, tFirstName, tLastName,tGender, tDOB, tCNIC, tEducation, tSalary, tJoinedOn, tAddress, tEmail, tContact1, tContact2, tContact3,tStatus) values ('" + tbIDCardNum.Text.Trim() + "' , '" + tbFirstName.Text.Trim() + "' , '" + tbLastName.Text.Trim() + "' , '" + gender + "' , '" + tbDOB.Text + "', '" + tbCNIC.Text + "' , '" + tbEducation.Text + "' , '" + tbSalary.Text.Trim() + "' , '" + tbDateOfJoining.Text.Trim() + "' , '" + tbAddress.Text.Trim() + "', '" + tbEmail.Text + "' , '" + tbContact1.Text + "' , '" + tbContact2.Text + "' , '" + tbContact3.Text + "',1)";

        cmd.Connection = conn;
        cmd.ExecuteNonQuery();

        cmd.Clone();
        conn.Close();

        HideStars();
        Refresh();

        MessageBox.Show("Saved");
   }
   catch (Exception ex)
   {
       if (ex.Message.Contains("Violation of PRIMARY KEY constraint "))
       {
           conn.Close();
           MessageBox.Show(ex.Message);
       }
       else
       {
           MessageBox.Show(ex.Message);
       }
   }
}

As I'm understanding it, what appears to be the main problem is that you check all fields in different if statements, but only the last has an else . 正如我所理解的那样,似乎主要问题是你检查不同if语句中的所有字段,但只有最后一个有其他字段。 As I'm assuming from your post, this is your problem; 正如我从你的帖子中假设的那样,这是你的问题; you want every textbox to have a value, before you start inserting it in the database, right? 你想让每个文本框都有一个值,然后才开始在数据库中插入它,对吗?

This is better explained if break up your code into something a bit more reusable, incidentally cleaning up stuff a bit as well. 如果将代码分解成更可重用的东西,偶然清理一些东西,可以更好地解释这一点。

First, start off by introducing a variable in your class that we can use to see if there are any empty fields: 首先,通过引入你的类变量,我们可以用它来看看是否有任何空字段开始:

private bool HasEmptyFields = false;

Next, let's create a simple helper that checks if the textbox is empty/null, updates the appropriate label's visiblity state and set 'HasEmptyFields' to true if it is indeed empty: 接下来,让我们创建一个简单的帮助器,检查文​​本框是否为空/ null,更新相应标签的visiblity状态,如果确实为空则将'HasEmptyFields'设置为true:

private void ValidateField(TextBox textBox, Label label) {

    // check if the textbox actually is null - or empty (""), which is a difference
    // the nifty helper string.IsNullOrEmpty() will help with that
    var fieldIsEmpty = string.IsNullOrEmpty(textBox.Text.Trim());

    // next, based on if the field is empty,  set the visibility of the label
    // don't worry, this is fancy syntax for a simple if...then...else
    label.Visibility = fieldIsEmpty ? Visibility.Visible : Visibility.Hidden;

    if (fieldIsEmpty) {
        // ONLY if this field is actually null, or empty, we make sure to 
        // inform the rest of the code this occ
        HasEmptyFields = true;
    }
}

With this in place, we can do something like: 有了这个,我们可以做一些事情:

ValidateField(tbIDCardNum, lblStarIDCardNum);
ValidateField(tbFirstName, lblStarFirstName);
// etc... continue doing this for all you fields

if (HasEmptyFields) {
    // ONLY if there is any field detected as being empty/null
    // we simply stop here (and skip the insert-into-db stuff)
    return;
} 

try 
{
    // if all fields indeed have a value, let's
    // continue with the insert-into-db stuff here

    conn.Open();
    ...
} 

Now there are certainly ways to makes this even prettier. 现在有一些方法可以让它变得更漂亮。 But this might help you a bit in the right direction. 但这可能会帮助你朝着正确的方向前进。 Also worth mentioning are some other comments, like preventing SQL injection (which is bound to happen), as well as looking into data validation tools so you don't have to code all this validation yourself. 另外值得一提的是一些其他注释,比如防止SQL注入 (必然会发生),以及查看数据验证工具,这样您就不必自己编写所有这些验证代码。 But that is not in the scope of this answer, obviously. 但显然,这不在这个答案的范围内。

如果您想要填写字段,那么您真的应该使用必填字段验证器 - 请参阅https://msdn.microsoft.com/en-us/library/5hbw267h%28VS.80%29.aspx?f=255&MSPPError = -2147217396

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM