获取DataGridView中的行号

时间:2009-09-10 01:17:15

标签: vb.net datagridview focus

如何获得行号DataGridView单元格?具体来说,如果用户选择了单个单元格,您如何获得该行号?它需要根据用户选择的内容访问特定的单元格。

我知道可以使用RemoveAt方法在Focus上删除,但你显然无法获得焦点上的行号?

感谢您的帮助!

5 个答案:

答案 0 :(得分:17)

您只需在RowIndex上使用current cell

var row = dataGridView1.CurrentCell.RowIndex;

答案 1 :(得分:2)

这个工作正常。

Private Sub DataGridView1_RowPrePaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint

If e.RowIndex >= 0 Then
        Me.DataGridView1.Rows(e.RowIndex).Cells(0).Value = e.RowIndex + 1
    End If
End Sub

答案 2 :(得分:0)

几乎相同,但您也可以使用此解决方案:

var row = dataGridView1.CurrentRow.Index

答案 3 :(得分:0)

如果您需要跟踪与DataGridView的用户交互,另一种方法: 在我的情况下,在使用Me.I_SelCol和Me.I_SelRow列和行坐标的一些通用函数中有额外的处理,但我没有显示,因为它与OP无关。

祝你好运, 罗布

Private Sub I_DataGridView_CurrentCellChanged(sender As Object, e As EventArgs) Handles I_DataGridView.CurrentCellChanged

        If Me.I_DataGridView.CurrentCellAddress.X < 0 Or Me.I_DataGridView.CurrentCellAddress.Y < 0 Then Exit Sub

        ' The Windows Me.I_DataGridView object will have already deselected the current cell and selected the 
        ' new cell as per user navigation using mouse or cursor keys.  We just need to store the current
        ' co-ordinates for the currently selected cell.

        Me.I_SelCol = Me.I_DataGridView.CurrentCellAddress.X
        Me.I_SelRow = Me.I_DataGridView.CurrentCellAddress.Y

Exit Sub

答案 4 :(得分:0)

如果您在datagridview的事件过程中发现“ e作为DataGridViewCellEventArgs”,则可以使用e.RowIndex获取行号,并使用e.ColumnIndex获取列号

Private Sub myDGV_CellLeave(sender As Object, e As DataGridViewCellEventArgs) Handles myDGV.CellLeave
    Dim myRow As Integer = e.RowIndex
End Sub

如果您按正常程序操作,则可以得到如下行号:

Private Sub btnGetRow_Click(sender As Object, e As EventArgs) Handles btnGetRow.Click
    dim myRow1 as Integer = 0
    dim myRow2 as Integer = 0
    myRow1 = myDGV.CurrentCell.RowIndex
    myRow2 = myDGV.CurrentRow.Index
End Sub