我一直有问题让我的插入工作。我一直在考虑它是基于两个组合框(1.cboCustomer 2.cboProduct)和一个文本框(RegistrationDate)的选定索引来完成的。我得到的最多的错误将与CustomerID为空有关;我认为这应该是自动生成的。当然,最让我困惑的是形式规范。 cboCustomer组合框必须显示客户的名称;这不是注册表的一部分。并且cboProduct组合框必须显示产品名称;这也与注册表无关。注册表是我需要创建插入的位置,但是组合框使用两种方法加载,即从客户和产品表中获取名称,该名称不能用于插入。其中,如果我尝试只插入注册日期,我会收到一条错误,指出ProductCode不能为空。如果AddRegistration方法尽管返回一个布尔值,仍然会运行insert,我也有点困惑。感谢您的帮助和时间。试图插入到数据库文件时出现C#问题
以下大部分代码已被更改几次,因为我尝试了几种解决方案,但都没有成功。
这是我必须提取值以传递给AddRegistration方法的代码。
public void PutRegistrationData(Registration registration)
{
registration.RegistrationDate = registrationDateTextBox.Text;
registration.ProductCode = productComboBox.SelectedValue.ToString();
}
这是触发的 AddRegistration插入表单上的按钮的代码。
private void btnRegister_Click(object sender, EventArgs e)
{
if (this.IsPresent(registrationDateTextBox.Text))
{
registration = new Registration();
this.PutRegistrationData(registration);
try
{
RegistrationDB.AddRegistration(registration);
MessageBox.Show("The product was entered successfully", "Registration Success");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
}
}
这是我在insertDB类的AddRegistration中插入的代码。
public static bool AddRegistration(Registration registration)
{
try
{
SqlConnection connection = TechSupportDB.GetConnection();
string insertStatement = "INSERT INTO Registrations (ProductCode, RegistrationDate" +
"VALUES (@ProductCode,@RegistrationDate)";
SqlCommand insertCommand = new SqlCommand(insertStatement, connection);
//insertCommand.Parameters.AddWithValue("@CustomerID", registration.CustomerID);
insertCommand.Parameters.AddWithValue("@ProductCode", registration.ProductCode);
insertCommand.Parameters.AddWithValue("@RegistrationDate", registration.RegistrationDate);
insertCommand.Connection = connection;
connection.Open();
insertCommand.ExecuteNonQuery();
connection.Close();
return true;
}
catch
{
return false;
}
}
}
}
插入命令缺少字段列表后面的关闭括号。这是一个错字吗? – Steve
也删除AddRegistration内部的空捕获,因为这样你就失去了真正的异常,告诉你什么是你的查询错误 – Steve
感谢您的答复。这可能是一个错字,我已经花了几个小时在这段代码上,并在这个过程中改变了插入几次。 – JaceLandrum