【问题标题】:inserting to ms sql database not null插入到 ms sql 数据库不为空
【发布时间】:2017-03-23 12:11:46
【问题描述】:

我有一个添加员工信息的表格,但我希望填写所有字段。我不知道这是否是正确的代码,但即使我不选中单选按钮和复选框,仍然会从文本框中将值添加到我的数据库中。我会感谢所有类型的回应。提前谢谢你。

if  (((textBox2.Text == string.Empty ||
            textBox3.Text == string.Empty ||
            textBox4.Text == string.Empty ||
            textBox5.Text == string.Empty ||
            textBox6.Text == string.Empty ||
            textBox7.Text == string.Empty ||
            textBox8.Text == string.Empty) &&
            (radioButton1.Checked == true ||
            radioButton2.Checked == true) &&
            (checkBox1.Checked == true ||
            checkBox2.Checked == true)))
        {
            MessageBox.Show("All fields are required!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        else
        {
            connect.Open();
            int age = Convert.ToInt32(textBox4.Text);
            string save = "INSERT INTO emp (empID, empLName, empFName, empAge, empGender, empAddress, empEmail, empUser, empPass, empType)  values('"
                + eid + "','" + textBox2.Text + "','" + textBox3.Text + "','" + age + "','" + gender + "','" + textBox5.Text + "','"
                + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + postn + "')";

            SqlCommand cmdsave = new SqlCommand(save, connect);
            cmdsave.ExecuteNonQuery();
            MessageBox.Show("Data Saved!");
            connect.Close();

            Admin adm = new Admin();
            adm.Show();
            this.Close();
        }

【问题讨论】:

  • 这里应该使用参数
  • 确保所有参数都根据数据类型正确传递
  • 有办法让你做到这一点,如果你有一个<div id="ParentControls" runat="server"> <contro A/> <contro B/> <contro C/> </div>,那么可以在这样的父控件中使用 foreach foreach (Control c in ParentControls) { if (c is TextBox) { if(c.Text == string.Empty) return true; } } return false; 你可以编写一个函数来传递一个控件(父级)并返回如果任何文本框为空,则为 true。在其他条件下使用复选框写入

标签: c# sql-server visual-studio-2013


【解决方案1】:

你的 IF 条件应该是这样的

if  ((textBox2.Text == string.Empty ||
        textBox3.Text == string.Empty ||
        textBox4.Text == string.Empty ||
        textBox5.Text == string.Empty ||
        textBox6.Text == string.Empty ||
        textBox7.Text == string.Empty ||
        textBox8.Text == string.Empty ||
        (radioButton1.Checked == false &&
        radioButton2.Checked == false ) ||
        !checkBox1.Checked ||
        !checkBox2.Checked ))

你可以使用 FOREACH

bool invalid = false;
foreach(Control ctr in this.Controls)
{
  if(ctr is TextBox)
  {
    if(ctr.Text == string.empty)
      {
        invalid = true;
        break;
      }
  }
}

if(invalid)
{
  MessageBox.Show("All fields are required!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    相关资源
    最近更新 更多