Visual Studio中调用AddNewCustomer提示无9参数重载问题求助
解决AddNewCustomer方法参数不匹配问题及代码优化建议
问题核心
你在按钮点击事件中直接传入9个字符串调用CustomerDAL.AddNewCustomer,但该方法的定义只接受单个CustomerModel类型的参数,因此Visual Studio提示找不到匹配的重载方法。
快速修复:正确调用方法
修改按钮点击事件中的代码,先创建CustomerModel实例,再将实例传入方法:
// 原错误调用 // int rowsAffected = CustomerDAL.AddNewCustomer(cmbxTitle.Text, txtForename.Text, ...); // 修正后的代码 var newCustomer = new CustomerModel( cmbxTitle.Text, txtForename.Text, txtSurname.Text, txtEmail.Text, txtStreetName.Text, txtTown.Text, txtCounty.Text, txtPostCode.Text, cmbxWeddingGiftList.Text ); int rowsAffected = CustomerDAL.AddNewCustomer(newCustomer);
重要代码优化建议(针对新手的关键注意事项)
1. 消除SQL注入风险
你当前用string.Format拼接SQL语句的写法存在严重的SQL注入漏洞,必须改用参数化查询,同时指定数据库列名(避免表结构变化导致错误):
public static int AddNewCustomer(CustomerModel newCustomer) { using (SqlConnection connection = new SqlConnection(_connectionString)) { connection.Open(); // 指定列名+参数化查询 string sqlQuery = @"INSERT INTO [Customer] (Title, Forename, Surname, Email, Streetname, Town, County, Postcode, WeddingGiftList) VALUES (@Title, @Forename, @Surname, @Email, @Streetname, @Town, @County, @Postcode, @WeddingGiftList)"; SqlCommand insertCommand = new SqlCommand(sqlQuery, connection); // 添加参数绑定 insertCommand.Parameters.AddWithValue("@Title", newCustomer.Title); insertCommand.Parameters.AddWithValue("@Forename", newCustomer.Forename); insertCommand.Parameters.AddWithValue("@Surname", newCustomer.Surname); insertCommand.Parameters.AddWithValue("@Email", newCustomer.Email); insertCommand.Parameters.AddWithValue("@Streetname", newCustomer.Streetname); insertCommand.Parameters.AddWithValue("@Town", newCustomer.Town); insertCommand.Parameters.AddWithValue("@County", newCustomer.County); insertCommand.Parameters.AddWithValue("@Postcode", newCustomer.Postcode); insertCommand.Parameters.AddWithValue("@WeddingGiftList", newCustomer.WeddingGiftList); int rowsAffected = insertCommand.ExecuteNonQuery(); // using块会自动关闭连接,无需手动调用connection.Close() return rowsAffected; } }
2. 修正表单验证逻辑
你当前用||(逻辑或)判断输入,只要有一个字段不为空就允许提交,这和"所有字段必须填写"的需求相反,应改为&&(逻辑与),同时用string.IsNullOrWhiteSpace更严谨地检查空值:
// 原错误判断 // if (cmbxTitle.Text != "" || txtForename.Text != "" || ...) // 修正后的验证逻辑 if (!string.IsNullOrWhiteSpace(cmbxTitle.Text) && !string.IsNullOrWhiteSpace(txtForename.Text) && !string.IsNullOrWhiteSpace(txtSurname.Text) && !string.IsNullOrWhiteSpace(txtEmail.Text) && !string.IsNullOrWhiteSpace(txtStreetName.Text) && !string.IsNullOrWhiteSpace(txtTown.Text) && !string.IsNullOrWhiteSpace(txtCounty.Text) && !string.IsNullOrWhiteSpace(txtPostCode.Text) && !string.IsNullOrWhiteSpace(cmbxWeddingGiftList.Text)) { // 创建CustomerModel并执行添加操作 } else { lblInfo.Visible = true; MessageBox.Show("请填写所有必填字段"); }
3. 移除冗余代码
using块会在代码执行完毕后自动释放数据库连接,因此无需手动调用connection.Close(),可以删除该行代码。
内容的提问来源于stack exchange,提问作者Jack___
相关产品推荐
相关产品推荐

