我有一个datagridview,里面装有我数据库中的一个表。当我对datagridview进行更改,然后单击更新按钮时,我希望它更新数据库。但是我得到这个错误:
必须声明缩放比例变量@ShortCompanyMessage
这是我按下按钮的代码。
string dataPath = "myPath";
string dataFile = "myDataFile";
string cfgFile;
using (StreamReader sr = new StreamReader(dataPath + dataFile))
{
cfgFile = sr.ReadLine();
}
cfgFields = Regex.Split(cfgFile, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
cfgFields[0] = cfgFields[0].Replace("\"", "");
strDataSource = cfgFields[0];
strDatabase = "Unity";
//cfgFields[1];
strLogin = cfgFields[2];
strPassword = cfgFields[3];
string connectionString = "Server=" + strDataSource + ";Database=" + strDatabase + ";User ID=" + strLogin + ";Password=" + strPassword + ";";
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
foreach (var row in GridViewCompanies.Rows)
{
var compID = row.Cells[0].Value.ToString();
var shortMessage = row.Cells[3].Value.ToString(); //get value of cells and update there and then? maybe?
var compMessage = row.Cells[4].Value.ToString();
SqlCommand update = new SqlCommand("UPDATE [Unity].[dbo].[Companies] SET shortMessage = @ShortCompanyMessage WHERE compID = @CompanyID", sqlConnection);
update.ExecuteNonQuery();
//SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(update);
}
任何帮助将不胜感激。
答案 0 :(得分:2)
您没有将@ShortCompanyMessage
和@CompanyID
传递给查询,因此像下面这样传递这些参数
foreach (var row in GridViewCompanies.Rows)
{
var compID = row.Cells[0].Value.ToString();
var shortMessage = row.Cells[3].Value.ToString(); //get value of cells and update there and then? maybe?
var compMessage = row.Cells[4].Value.ToString();
SqlCommand update = new SqlCommand("UPDATE [Unity].[dbo].[Companies] SET shortMessage = @ShortCompanyMessage WHERE compID = @CompanyID", sqlConnection);
update.Parameters.AddWithValue("@ShortCompanyMessage", shortMessage); <= Here i added parameter to your command
update.Parameters.AddWithValue("@CompanyID", compID); <= Here i added parameter to your command
update.ExecuteNonQuery();
//SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(update);
}