Winforms 无法转换参数值--更新对DataGridView的更改
当用户修改Windows窗体上DataGridView中的单元格时,我尝试更新SQL Server数据库。我得到了错误Winforms 无法转换参数值--更新对DataGridView的更改,winforms,visual-studio-2008,datagridview,sql-server-2008-r2,Winforms,Visual Studio 2008,Datagridview,Sql Server 2008 R2,当用户修改Windows窗体上DataGridView中的单元格时,我尝试更新SQL Server数据库。我得到了错误 Failed to convert parameter value from a DataGridViewTextBoxCell to a String 在“update.ExecuteNonQuery()”行中。我正在运行Visual Studio C#Express 2008和SQL Server Management Studio Express 2008 R2。如蒙协
Failed to convert parameter value from a DataGridViewTextBoxCell to a String
在“update.ExecuteNonQuery()”行中。我正在运行Visual Studio C#Express 2008和SQL Server Management Studio Express 2008 R2。如蒙协助,将不胜感激
private void buttonUpdate_Click(object sender, EventArgs e)
{
// Create the UpdateCommand.
SqlCommand update = new SqlCommand(
"UPDATE clients SET " +
"client_name_first = @client_name_first " +
"WHERE client_id = @modifiedRowNum;", connect);
// Add the parameters for the UpdateCommand.
update.Parameters.Add(
"@client_name_first", SqlDbType.VarChar, 50).Value =
dgvClients.Rows[dgvClients.CurrentCell.RowIndex + 1].Cells[dgvClients.CurrentCell.ColumnIndex];
update.Parameters.Add(
"@modifiedRowNum", SqlDbType.Int, 5).Value = dgvClients.CurrentCell.RowIndex + 1;
// Execute the operation.
update.ExecuteNonQuery();
}
发生错误的原因是您没有在
单元格
之后指定.Value
属性。您试图分配的是DataGridViewCell
,而不是该单元格的值。可以使用.value
属性从单元格中检索该值
即.var value=dgv.Rows[RowIndex].Cell[ColumnIndex].value
在代码中,只需在.Cells[dgvClients.CurrentCell.ColumnIndex]之后添加.Value
update.Parameters.Add("@client_name_first", SqlDbType.VarChar, 50).Value = dgvClients.Rows[dgvClients.CurrentCell.RowIndex + 1].Cells[dgvClients.CurrentCell.ColumnIndex].Value;
完整的代码如下所示
// Create the UpdateCommand.
SqlCommand update = new SqlCommand(
"UPDATE clients SET " +
"client_name_first = @client_name_first " +
"WHERE client_id = @modifiedRowNum;", connect);
// Add the parameters for the UpdateCommand.
update.Parameters.Add(
"@client_name_first", SqlDbType.VarChar, 50).Value =
dgvClients.Rows[dgvClients.CurrentCell.RowIndex + 1].Cells[dgvClients.CurrentCell.ColumnIndex].Value;
update.Parameters.Add(
"@modifiedRowNum", SqlDbType.Int, 5).Value = dgvClients.CurrentCell.RowIndex + 1;
// Execute the operation.
update.ExecuteNonQuery();