简体   繁体   中英

Select first visible cell of new row in DataGridView

I'm trying to focus input and fire the editing event on each new row that I add to a DataGridView in my form.

This is the code I am trying to user to achieve this.

Private Sub grd_GoldAdders_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles grd_GoldAdders.RowsAdded
        Dim grid As DataGridView = DirectCast(sender, DataGridView)

        grid.ClearSelection()

        If grid.Rows(e.RowIndex).Cells("grid_flag").FormattedValue = Constants.[New] Then

            For Each cell As DataGridViewCell In grid.Rows(e.RowIndex).Cells
                If Not cell.Visible Then Continue For
                grid.CurrentCell = cell 
                grid.BeginEdit(False)
                Exit For
            Next

        End If

    End Sub

The "grid_flag" is a hidden cell which is used to store custom states for a row.

Prior to adding a row, this is what we see on the form: 在我们添加新行之前。

This is what we see when we actually try and add a new row: 单击行添加按钮。

Notice that both the column 0,0 and the first visible column of the new row are selected, but the column 0,0 has the focus. I do not wish for 0,0 to either get selected or have the focus. I also see here that the row indicator is pointing at row 0 too...

This is how I would like to see things after clicking my Add button: 单击“添加”按钮所需的结果。

Does anyone know where I am going wrong with the code? I've searched SO for the most part of the day trying to solve this one.

Instead of using your DataGridView's RowAdded event to set the CurrentCell, add the following code wherever you're adding a new record to your DGV (in your Add button's Click event I assume):

''# Add the new record to your Data source/DGV.

For Each row As DataGridViewRow In grd_GoldAdders.Rows
    If row.Cells("grid_flag").FormattedValue = Constants.[New] Then 
        grd_GoldAdders.CurrentCell = row.Cells("AssySiteColumn")  ''# I'm calling the first column in your DGV 'AssySiteColumn'.
        grd_GoldAdders.BeginEdit(False)
        Exit For
    End If
Next

This code simply loops through all the rows in your DGV and specifies as the CurrentCell the first cell in the first row with your Constants.[New] flag value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM