datagridviewdatagridviewcolumndatagridviewbuttoncolumn

Disable Column Header click on datagridview vb.net


I have created a command button for each row on a datagridview.


datagridview row buttons


The code is working fine.

    Private Sub dgv_employees_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv_employees.CellClick
    'If dgv_employees.Columns(e.ColumnIndex).HeaderText = "Edit" Then
    If e.ColumnIndex = 16 Then
        'dgv_employees.Columns(16).SortMode = DataGridViewColumnSortMode.NotSortable
        Dim constr As String = "Data Source=CARSON-PC;Initial Catalog=payroll;Integrated Security=True"
        Dim row As DataGridViewRow = dgv_employees.Rows(e.RowIndex)
        Dim ds As New DataSet()

        If MessageBox.Show(String.Format("Do you want to delete ID: {0}", row.Cells("empNum").Value), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
            Using con As New SqlConnection(constr)
                Using cmd As New SqlCommand("DELETE FROM [dbo].[emp_personal] WHERE empNum = @empNum", con)
                    cmd.CommandType = CommandType.Text
                    cmd.Parameters.AddWithValue("@empNum", row.Cells("empNum").Value)
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using
            End Using

            Me.BindGrid()
        End If

    End If

End Sub

However, whenever I click the column header, it gives me an error.

How can I fix this?


error


Solution

  • Posting the code I've came up so others may have reference.

    I deleted this line Dim row As DataGridViewRow = dgv_employees.Rows(e.RowIndex)

    This one works now for me:

            If e.RowIndex >= 0 AndAlso e.ColumnIndex = 16 Then
            If MessageBox.Show(String.Format("Do you want to delete ID: {0}", dgv_employees.Rows(e.RowIndex).Cells("empNum").Value), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
                Using con As New SqlConnection(constr)
                    Using cmd As New SqlCommand("DELETE FROM [dbo].[emp_personal] WHERE empNum = @empNum", con)
                        cmd.CommandType = CommandType.Text
                        cmd.Parameters.AddWithValue("@empNum", dgv_employees.Rows(e.RowIndex).Cells("empNum").Value)
                        con.Open()
                        cmd.ExecuteNonQuery()
                        con.Close()
                    End Using
                End Using
    
                Me.BindGrid()
            End If
        End If