从表格DGV更新表格

时间:2014-03-03 20:49:53

标签: vb.net winforms datagridviewcombobox

我有一个DGV,它从我的应用程序中的存储过程加载:

Dim conn As New SqlConnection(My.Resources.FCLRptConn)
            Dim cmd As New SqlCommand("spFCLEditAgentAssignments", conn)
            cmd.CommandType = CommandType.StoredProcedure
            Dim ds As New DataSet
            Dim DA As New SqlDataAdapter(cmd)

            cmd.Parameters.AddWithValue("@ActiveIndicator", Me.tscmbActiveIndicator.ComboBox.SelectedValue)

            DA.Fill(ds)

            Me.dgvAgentAssignment.DataSource = ds.Tables(0)

在此之前,我添加了一个DataGridViewComboBox列,该列绑定到DGV中的一列:

Dim conn As New SqlConnection(My.Resources.FCLRptConn)
            Dim cmd As New SqlCommand("spFCLLUVTeamAssignment", conn)
            Dim da As New SqlDataAdapter(cmd)
            Dim TeamAssign As New DataTable

            da.Fill(TeamAssign)

            With FCLTeam
                .DataPropertyName = "FCLTeamID"
                .Name = "FCLTeamID"
                .DataSource = TeamAssign
                .DisplayMember = "FCLTeamName"
                .ValueMember = "FCLTeamID"
                .AutoSizeMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
            End With

当表格加载时,我想出了一个 “对象引用未设置为对象的实例”错误。这发生在这段代码中:

 cmd.CommandText = "UPDATE tblFCLAgentAssignment SET [" & ColumnName & "] = '" & _
                             ConvertVBBooleanToSQLBit(dgvAgentAssignment.CurrentRow.Cells(ColumnName).Value) & _
                            "' WHERE RefID = '" & dgvAgentAssignment.CurrentRow.Cells("RefID").Value & "'"

以上代码用于更新通过DGV更新的字段或单元格。

在我跳过错误后,我可以更新'FCLTeamID'字段,没有任何问题。在装载时我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

 If Not String.IsNullOrEmpty(ColumnName) Then
            cmd.CommandText = "UPDATE tblFCLAgentAssignment SET [" & ColumnName & "] = '" & _
                                         ConvertVBBooleanToSQLBit(dgvAgentAssignment.CurrentRow.Cells(ColumnName).Value) & _
                                        "' WHERE RefID = '" & dgvAgentAssignment.CurrentRow.Cells("RefID").Value & "'"
        End If

这解决了ColumnName问题,如果它是空的,则不会尝试更新表