【问题标题】:Failed to convert parameter value -- Updating changes to a DataGridView无法转换参数值 - 更新对 DataGridView 的更改
【发布时间】:2014-08-21 00:44:01
【问题描述】:

当用户修改 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。任何帮助将不胜感激。

    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();
    }

【问题讨论】:

    标签: winforms visual-studio-2008 datagridview sql-server-2008-r2


    【解决方案1】:

    发生错误是因为您在Cell 之后没有指定.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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多