从 GridView C# 更新多条记录

Update Multiple Records From a GridView C#

我正在尝试更新数据网格中的多行,代码完成了工作,但我似乎仍然得到

Object reference not set to an instance of an object

当我检查记录时,所需的状态会相应地针对 gridview 中的选定记录进行更新。

private void UpdateWorkerStatus()
{
    SqlCommand cmdUpdate = new SqlCommand(@"UPDATE Workers2
                                       SET WorkerStatus = @WorkerStatus
                                       WHERE FullName = @FullName", cn);

    cmdUpdate.Parameters.AddWithValue("@WorkerStatus", SqlDbType.VarChar).Value = txtWorkerStatus.Text;
    cmdUpdate.Parameters.AddWithValue("@FullName", SqlDbType.VarChar).Value = txtFullName.Text;

    foreach (DataGridViewRow row in grdWorkers.Rows)
    {
        cmdUpdate.Parameters["@WorkerStatus"].Value = row.Cells["WorkerStatus"].Value.ToString();
        cmdUpdate.Parameters["@FullName"].Value = row.Cells["FullName"].Value.ToString();
        cmdUpdate.ExecuteNonQuery();
    }
}

提前致谢! :)

试试这个,而不是 .ToString() 使用 Convert.Tostring( row.Cells["FullName"].Value) "WorkStatus"

相同

由于您没有向我们提供异常抛出位置的信息,我假设它是在 .ToString() 调用之一上,因为这些是最有可能的。可能 WorkerStatus 或 FullName 的值之一为 null,导致调用 .ToString() 方法时出现异常。

我会在调用 .ToString() 之前检查空值。如果您尝试读取的值为空,这使您能够用有意义的内容填充参数值:

if (row.Cells["WorkerStatus"].Value != null)
    cmdUpdate.Parameters["@WorkerStatus"].Value = row.Cells["WorkerStatus"].Value.ToString();
else
    cmdUpdate.Parameters["@WorkerStatus"].Value = string.Empty // or some meaningful default value of your chosing

您可以使用以下方法将此语句缩减为一行:

cmdUpdate.Parameters["@WorkerStatus"].Value = (row.Cells["WorkerStatus"].Value != null) ? row.Cells["WorkerStatus"].Value.ToString() : string.Empty;

当然你也应该为 FullName 做同样的事情。

private void UpdateWorkerStatus()
{
    SqlCommand cmdUpdate = new SqlCommand(@"UPDATE Workers2
                                   SET WorkerStatus = @WorkerStatus
                                   WHERE FullName = @FullName", cn);

    cmdUpdate.Parameters.AddWithValue("@WorkerStatus", SqlDbType.VarChar).Value = txtWorkerStatus.Text;
    cmdUpdate.Parameters.AddWithValue("@FullName", SqlDbType.VarChar).Value = txtFullName.Text;

    foreach (DataGridViewRow row in grdWorkers.Rows)
    {
        cmdUpdate.Parameters["@WorkerStatus"].Value = row.Cells["WorkerStatus"].Value!=DBNull.Value? row.Cells["WorkerStatus"].Value.ToString():"";
        cmdUpdate.Parameters["@FullName"].Value = row.Cells["FullName"].Value!= DBNull.Value ? row.Cells["FullName"].Value.ToString():"";
        cmdUpdate.ExecuteNonQuery();
    }
}