Reputation: 332
I'm trying to update a SQL Server database when the user modifies a cell in a DataGridView on a Windows Form. I get the error
Failed to convert parameter value from a DataGridViewTextBoxCell to a String
on the line 'update.ExecuteNonQuery()'. I'm running Visual Studio C# Express 2008 and SQL Server Management Studio Express 2008 R2. Any assistance would be greatly appreciated.
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();
}
Upvotes: 0
Views: 193
Reputation: 6849
The error is occurred because you have not specified .Value
property after Cell
. You are trying to assign DataGridViewCell
instead of value of that cell. The value can be retrieved from cell by using .Value
property.
ie. var value = dgv.Rows[RowIndex].Cell[ColumnIndex].Value
.
and in the code you just need to add .Value
after ..Cells[dgvClients.CurrentCell.ColumnIndex]
update.Parameters.Add("@client_name_first", SqlDbType.VarChar, 50).Value = dgvClients.Rows[dgvClients.CurrentCell.RowIndex + 1].Cells[dgvClients.CurrentCell.ColumnIndex].Value;
the complete code will be look like this
// 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();
Upvotes: 1