【问题标题】:My if else statement doesn't seems to work. How do I prevent sending empty data to the Database?我的 if else 语句似乎不起作用。如何防止向数据库发送空数据?
【发布时间】:2014-01-31 13:06:29
【问题描述】:
 private void btnSubmitConsultation_Click(object sender, EventArgs e)
    {
        int medicalHistoryResult = insertMedicalHistory();

        if (medicalHistoryResult > 0)
        {
            MessageBox.Show("Document(s) submitted", "Success");
        }

        else
        {
            MessageBox.Show("Insert Fail");
        }


        int allergiesResult = insertAllergies();

        if (allergiesResult > 0)
        {
            if (txtNewAllergy.Text != null || txtReactions.Text != null)
            {
                if (txtNewAllergy.Text == null)
                {
                    MessageBox.Show("Please key in the Type of the allergy", "WARNING");
                }
                else if (txtReactions.Text == null)
                {
                    MessageBox.Show("Please key in the Description of the allergy", "WARNING");
                }
            }
            else
            {
                MessageBox.Show("Submitted, fool");
            }
        }
        else
        {
            MessageBox.Show("Not submitted, fool");
        }


    }

嗯,medicalHistoryResult 似乎工作正常,但 allergiesResult 根本没有做任何事情。

我的 insertAllergies 函数只是一个普通的 INSERT,没什么特别的。

这是我的 insertAllergies 函数:

private int insertAllergies()
    {
        int allergiesResult = 0;

        string strConnectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        SqlConnection connection = new SqlConnection(strConnectionString);

        try
        {
            string strPatient = "SELECT patientID FROM PATIENT WHERE patientID=@searchPatientID";
            SqlCommand cmdPatient = new SqlCommand(strPatient, connection);
            cmdPatient.Parameters.AddWithValue("@searchPatientID", txtPatientID.Text);

            string strAllergies = "INSERT ALLERGIES (allergyType, allergyDesc, patientID) " +
                "VALUES (@insertType, @insertDesc, @insertPatient)";
            SqlCommand cmdAllergies = new SqlCommand(strAllergies, connection);

            connection.Open();

            cmdAllergies.Parameters.AddWithValue("@insertType", txtNewAllergy.Text);
            cmdAllergies.Parameters.AddWithValue("@insertDesc", txtReactions.Text);

            SqlDataReader readPatient = cmdPatient.ExecuteReader();
            if (readPatient.Read())
            {
                string addPatient = readPatient["patientID"].ToString();
                cmdAllergies.Parameters.AddWithValue("@insertPatient", addPatient);
            }
            readPatient.Close();

            allergiesResult = cmdAllergies.ExecuteNonQuery();


        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
        finally
        {
            connection.Close();
        }

        return allergiesResult;
    }

--------------------------更新------ -------------------------------------------------------

好的,这是我的新逻辑:

       if (string.IsNullOrEmpty(txtNewAllergy.Text) || string.IsNullOrEmpty(txtReactions.Text))
       {
           if (string.IsNullOrEmpty(txtNewAllergy.Text) && txtReactions.Text != null)
           {
               MessageBox.Show("Please key in the Type of the allergy", "WARNING");
           }
           else if (string.IsNullOrEmpty(txtReactions.Text) && txtNewAllergy.Text != null)
           {
               MessageBox.Show("Please key in the Description  of the allergy", "WARNING");
           }
       }
       else if (txtNewAllergy.Text != null && txtReactions.Text != null)
       {
           int allergiesResult = insertAllergies();
       }

它似乎有效,但只有一个缺陷:当我将两个文本都提交为空时,会弹出“请输入过敏类型”。如果两个文本都是空的,我该怎么做,它什么都不做。

【问题讨论】:

  • "" is != null 所以它会通过使用if(txtNewAllergy.Text != null && txtNewAllergy.Text != string.Empty || txtReactions.Text != null&& txtReactions.Text != string.Empty)
  • 您指定allergiesResult 没有做任何事情。您希望 int 提供什么样的功能? 编辑:基本上与@Grant 相同的问题。
  • @Grant 有一个什么都不做的代码路径......(没有任何消息)
  • 我重新表述我的问题:insertAllergies 在什么情况下返回大于 0 的数字?
  • int allergiesResult = insertAllergies(); ?

标签: c# database winforms visual-studio-2010 if-statement


【解决方案1】:

如果txtNewAllergytxtReactionsTextBox,那么永远不会期望.Textnull;您需要检查一个空的非空字符串。试试string.IsNullOrEmpty(...)

if (!string.IsNullOrEmpty(txtNewAllergy.Text)
    || !string.IsNullOrEmpty(txtReactions.Text))

为了方便,我们倾向于使用扩展方法:

public static bool HasValue(this string value) {
    return !string.IsNullOrEmpty(value);
}

那么就是:

if (txtNewAllergy.Text.HasValue() || txtReactions.Text.HasValue())

另外:请注意有一个什么都不做的代码路径(请参阅“这里发生了什么?”):

if (allergiesResult > 0)
{
    if (txtNewAllergy.Text != null || txtReactions.Text != null)
    {
        if (txtNewAllergy.Text == null)
        {
            MessageBox.Show("Please key in the Type of the allergy", "WARNING");
        }
        else if (txtReactions.Text == null)
        {
            MessageBox.Show("Please key in the Description of the allergy", "WARNING");
        }
        else
        {
            // WHAT HAPPENS HERE?
        }
    }
    else
    {
        MessageBox.Show("Submitted, fool");
    }
}
else
{
    MessageBox.Show("Not submitted, fool");
}

【讨论】:

  • 另外,如果合适并使用 .NET 4.0 或更高版本,请考虑 IsNullOrWhitespace()。
  • @bland !String.IsNullOrEmpty 和 .Length > 0 之后检查会更好。
  • @MaxMommersteeg 检查是否不为空后,您忘记了对 Trim 的调用。此外,IsNullOrWhitespace 根据documentation 进行了优化。并且并不总是需要检查空格,因此仅在适当的情况下建议这样做。
【解决方案2】:

您的INSERT 查询缺少INTO 关键字。

尝试将strAllergies 更改为:

string strAllergies = @"INSERT INTO ALLERGIES (allergyType, allergyDesc, patientID)
                        VALUES (@insertType, @insertDesc, @insertPatient)";

【讨论】:

  • 感谢您指出这一点,但这并没有改变任何事情。
  • 您的查询实际上是否插入了任何内容?据我所知,不是。
猜你喜欢
  • 1970-01-01
  • 2021-12-07
  • 2018-08-25
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
相关资源
最近更新 更多