如何对某些空文本框进行验证

时间:2017-10-04 17:37:16

标签: c#

如果txtPName和txtAddress为空,我怎么能对它进行验证我无法继续提交并弹出一个消息框。

private void btnSubmit_Click(object sender, EventArgs e)
    {

        string insertQuery = "INSERT INTO patientdb.addpatient(PatientName,MobileNumber,Occupation,Gender,Address,Age,PhoneNumber,MedicalHistory,ChiefComplaint) VALUES ('" + txtPName.Text + "','" + txtMNum.Text + "','" + txtOccup.Text + "','" + comboBox1.Text + "','" + txtAddress.Text + "','" + txtAge.Text + "','" + txtPNum.Text + "','" + rtbMHistory.Text + "','" + rtbCC.Text + "')";
        con.Open();
        MySqlCommand command = new MySqlCommand(insertQuery, con);

        try
        {
            if (command.ExecuteNonQuery() == 1)
            {
                MessageBox.Show("Data Inserted");
                txtPName.Text = "";
                txtMNum.Text = "";
                txtPNum.Text = "";
                txtAddress.Text = "";
                txtAge.Text = "";
                txtOccup.Text = "";
                rtbMHistory.Text = "";
                rtbCC.Text = "";
                comboBox1.Text = " ";
            }
            else
            {
                MessageBox.Show("Data Not Inserted");
            }
        }

1 个答案:

答案 0 :(得分:0)

您可以在执行其余代码之前添加验证检查。在验证失败后,调用return将立即离开该方法。

private void btnSubmit_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(txtPName.Text) || string.IsNullOrEmpty(txtAddress.Text))
    {
        MessageBox.Show("Missing Data");
        return;
    }

// Your code here...