【发布时间】:2017-04-24 04:20:37
【问题描述】:
所以我正在尝试使用 Visual Studio 在 C# 中创建一个 asp.net Web 应用程序。我的一个网页有两个单选按钮(添加父级和添加子级),根据选择的一个,许多文本框将变得可见并且必须填写以进行注册。我已成功将提交按钮连接到我的数据库,并且在文本框中输入的值正在正确地发送到我数据库中相应的“父母”和“孩子”表。
我现在遇到的问题是我正在尝试设置它,以便所有文本框中都必须有一个条目,如果没有,则会出现一个消息框,告诉用户他们需要填写所有字段。我实际上已经设法让它工作,我遇到的问题是,即使它告诉你需要填写所有字段,它仍然会将填写的值发送到数据库。
我想知道如果没有填写任何文本框,是否有办法不打开数据库连接。我在下面附上了我的代码,谢谢:)。
protected void submitBtn_Click(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection("Data Source=THEBEAST;Initial Catalog=newregDB;Integrated Security=True;Pooling=False");
{
if (firstNameBox.Text == "" || surnameBox.Text == "" || dayDobList.Text == "" || monthDobList.Text == "" || yearDobList.Text == "" || genderList.Text == "" || postcodeBox.Text == "" || teleBox.Text == "" || emailBox.Text == "" || userBox.Text == "" || passwordBox.Text == "")
Response.Write("<script>alert('Please ensure all fields have an entry');</script>");
if (parentRadBtn.Checked)
{
SqlCommand pa = new SqlCommand("INSERT INTO parent(parentID, firstname, surname, postcode, telephone, email, password) VALUES (@parentID, @firstname, @surname, @postcode, @telephone, @email, @password)", connect);
pa.Parameters.AddWithValue("@parentID", userBox.Text);
pa.Parameters.AddWithValue("@firstname", firstNameBox.Text);
pa.Parameters.AddWithValue("@surname", surnameBox.Text);
pa.Parameters.AddWithValue("@postcode", postcodeBox.Text);
pa.Parameters.AddWithValue("@telephone", teleBox.Text);
pa.Parameters.AddWithValue("@email", emailBox.Text);
pa.Parameters.AddWithValue("@password", passwordBox.Text);
connect.Open();
pa.ExecuteNonQuery();
connect.Close();
if (IsPostBack)
{
userBox.Text = "";
firstNameBox.Text = "";
surnameBox.Text = "";
postcodeBox.Text = "";
teleBox.Text = "";
emailBox.Text = "";
passwordBox.Text = "";
}
}
else if (childRadBtn.Checked)
{
SqlCommand ca = new SqlCommand("INSERT INTO children(childID, firstname, dob, gender, password) VALUES (@childID, @firstname, @dob, @gender, @password)", connect);
ca.Parameters.AddWithValue("@childID", userBox.Text);
ca.Parameters.AddWithValue("@firstname", firstNameBox.Text);
ca.Parameters.AddWithValue("@dob", dayDobList.Text + monthDobList.Text + yearDobList.Text);
ca.Parameters.AddWithValue("@gender", genderList.Text);
ca.Parameters.AddWithValue("@password", passwordBox.Text);
connect.Open();
ca.ExecuteNonQuery();
connect.Close();
if (IsPostBack)
{
userBox.Text = "";
firstNameBox.Text = "";
dayDobList.Text = "";
monthDobList.Text = "";
yearDobList.Text = "";
genderList.Text = "";
passwordBox.Text = "";
}
}
}
【问题讨论】:
-
哈哈@
I can't stop my web app sending values to my database。它变得有知觉了! -
if...else是编程的 101。 -
我知道这听起来很荒谬,但在我的脑海中听起来更好。我知道可能有另一种更简单的方法,但我似乎找不到它!
-
需要更好地掌握 If/Else 的工作原理。 msdn.microsoft.com/en-us/library/5011f09h.aspx
-
天哪,好尴尬。我希望我能让史蒂夫成为答案,否则我错过了制作父单选按钮。那解决了它。谢谢你:)
标签: c# sql asp.net database visual-studio