如何在最后位置添加行并从当前位置删除行在VB.net的DataGridview中

时间:2016-04-15 08:52:32

标签: vb.net

我正在使用vb./net。  在网格视图中每个都有两个按钮Like +和 - 如果用户单击+然后一行需要在最后位置添加,如果用户单击 - 那么一行需要从当前位置删除

我已尝试使用以下代码,但它会给我一个错误

Private count As Integer = 1
    Private Sub dgvSourcePath_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSourcePath.CellContentClick
        If e.ColumnIndex = 2 Then
            dgvSourcePath.Rows.Insert(count)
        End If
        If e.ColumnIndex = 3 Then
            count -= 1
            dgvSourcePath.Rows.RemoveAt(count)
        End If
        If e.ColumnIndex = 1 Then
            OpenSourceFileDialog.ShowDialog()
            If Windows.Forms.DialogResult.OK Then
                dgvSourcePath.CurrentRow.Cells(0).Value = OpenSourceFileDialog.FileName
            End If
        End If
        dgvSourcePath.Refresh()
    End Sub

1 个答案:

答案 0 :(得分:0)

请试试这个:

      Private Sub dgvdatos_CellContentClick(sender As DataGridView, e As DataGridViewCellEventArgs) Handles dgvdatos.CellContentClick
Try

  dgvdatos.EndEdit()

  If TypeOf (sender.CurrentCell) Is DataGridViewButtonCell Then

    If e.ColumnIndex = 2 Then
      dgvdatos.Rows.Insert(sender.RowCount - 1)
    End If
    If e.ColumnIndex = 3 And sender.Rows.Count > 1 Then
      count -= 1
      dgvdatos.Rows.RemoveAt(e.RowIndex)
    End If
    If e.ColumnIndex = 1 Then
      OpenSourceFileDialog.ShowDialog()
      If DialogResult.OK Then
        dgvdatos.CurrentRow.Cells(0).Value = OpenSourceFileDialog.FileName
      End If
    End If
    dgvdatos.Refresh()
  End If
Catch ex As Exception

  MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

End Sub