我的程序似乎跳过了我的“如果”语句
本文关键字:我的 如果 语句 程序 过了 | 更新日期: 2023-09-27 18:35:51
我有一个向 Access 数据库提交信息的 C# 应用程序。我填写了三个必填框,然后单击"提交"。当用户单击按钮时,脚本应按以下方式响应:
第 1 步。查看数据库表 A,以查看数据库中是否存在 textBox1 中的值。
第 2 步。如果该值存在,则将 textBox1、textBox2 和 textBox3 的值分别添加到数据库表 B 列中。
第 3 步。如果三个文本框中的任何一个留空,则显示一条消息。
第 4 步。如果 textBox1 中的值不在数据库表中,则显示一条消息。(最终,我计划将消息替换为数据库字段的默认填充)
问题: 当我运行程序时,在上述任何一种情况下,结果是上面的步骤4。它似乎跳过了第一个"如果"语句,直接跳到"else"结果。
任何帮助解决这个问题,将不胜感激!"私人无效"代码如下。提前谢谢。
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand("select * from script_Orders where cust_Name = @UserID", vcon);
OleDbParameter param = new OleDbParameter();
param.ParameterName = "@UserID";
param.Value = textBox1.Text;
cmd.Parameters.Add(param);
OleDbDataReader reader = cmd.ExecuteReader();
{
if (reader.HasRows)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("You must fill in all fields.");
return;
}
else
{
OleDbCommand dbCommand;
OleDbDataReader dbReader;
new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;data source=C:'Search'Database.accdb");
dbCommand = new OleDbCommand("select count(*) as Record_Count from script_received", vcon);
dbReader = dbCommand.ExecuteReader();
if (dbReader.Read() == true)
rowCount = dbReader["Record_Count"].ToString();
else
return;
var date = DateTime.Now.ToString("MM/dd/yyyy");
{
using (OleDbCommand command = new OleDbCommand("INSERT INTO script_Received (script, qty, emp_id, received_Date) VALUES (@script,@qty,@emp_Id,@rec_date)"))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("@script", OleDbType.Integer).Value = textBox1.Text;
command.Parameters.Add("@qty", OleDbType.VarChar).Value = textBox2.Text;
command.Parameters.Add("@emp_id", OleDbType.VarChar).Value = textBox3.Text;
command.Parameters.Add("@rec_date", OleDbType.Date).Value = date;
command.Connection = vcon;
command.ExecuteNonQuery();
}
this.textBox1.Clear();
this.textBox2.Clear();
this.textBox1.Focus();
}
}
}
else
{
MessageBox.Show("The value of textBox1 is not in the orders table");
return;
}
}
}
如果它跳转到if(reader.HasRows)
的else
而不引发任何异常,则reader
不得null
,并且其HasRows
属性必须false
。 这意味着您的查询已成功执行,但没有返回任何行。
您可以尝试手动运行 select
语句,这可能有助于您了解问题所在。最有可能的是,您在文本框中键入的内容与任何cust_name
值都不匹配。