how to set focus to a textbox when clicking a cell in a datagrid?

Please help!!!!!!!!

I've try to call textbox.focus in a method that handle datagrid.CurrentCellChanged but it doesn't work.

what should i do  stop programming


Answer this question

how to set focus to a textbox when clicking a cell in a datagrid?

  • johnfi

    I found an other way to resolve this issue for my use : I put the focus when the mouseup event is fired instead of the currentcellchanged
  • UmaMohan

    Right -- so the problem is that the CurrentCellChanged fires telling you that we're changing to the new cell.  You then set your TextBox to be focused, and it is -- really briefly.  The textbox in the grid then rips focus away.

    I don't know of a nice way around this, so I'll give you a slightly non-nice way: when the currentchanged fires you say "I'd really like focus to go to my textbox" by setting a flag.  When the grid's TextBox gets focus, you rip focus away to your textbox (it's only fair).

        Dim dt As DataTable
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            dt = New DataTable("foo")
            dt.Columns.Add("id")
            dt.Columns.Add("f")
            dt.Rows.Add(New Object() {"a", True})

            dt.AcceptChanges()

            Dim ts As New DataGridTableStyle()
            ts.MappingName = dt.TableName
            DataGrid1.TableStyles.Add(ts)

            Dim tc As New DataGridTextBoxColumn()
            Dim dc As DataColumn
            For Each dc In dt.Columns
                tc = New DataGridTextBoxColumn()
                tc.MappingName = dc.ColumnName
                AddHandler tc.TextBox.Enter, AddressOf FocusedTextBoxColumn
                ts.GridColumnStyles.Add(tc)
            Next
            DataGrid1.DataSource = dt

        End Sub

        Dim focusTextBox As Boolean = False
        Private Sub DataGrid1_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGrid1.CurrentCellChanged
            focusTextBox = True
        End Sub

        Sub FocusedTextBoxColumn(ByVal o As Object, ByVal e As EventArgs)
            If focusTextBox Then
                textBox1.Focus()
                focusTextBox = False
            End If
        End Sub

  • how to set focus to a textbox when clicking a cell in a datagrid?