0

enter image description here

Pressing Tab key on Button Refresh is setting focus on the dropdown list but I need to set focus on Checkbox column and first row of grid when the grid datasource is not null else the next control, however it is selecting the given cell only. I have set tabIndex property in sequence, please tell me where i am wrong, here is my code:

private void btnRefresh_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
  if (e.KeyCode == Keys.Tab)
  {
     if (grid.DataSource != null)
     {
       grid.Focus();
       grid.CurrentCell = this.grid[1, 0];
       grid.CurrentCell.Selected = true;
       grid.BeginEdit(false); 
     }
     else
     {
       btnCancel.Focus();
     }
   }
}
Mahrukh Mehmood
  • 258
  • 2
  • 5
  • 17

1 Answers1

1

Have you seen this post? Seems like your use of the index is of Grid[x,y].

Try

grid.Rows[1].Cells[0]

However, this wil select only the cell (first cell, second row by the way). If you want to select the entire row, try

grid.Rows.First().Selected = True

Hope it helps.

Community
  • 1
  • 1
Rik
  • 3,647
  • 2
  • 25
  • 34
  • Yes i tried this way earlier, then i changed to this, it is just selecting the grid cell but not setting focus : ( – Mahrukh Mehmood May 20 '15 at 06:39
  • Try to execute the focus command last in row. ... if (grid.DataSource != null) { ... grid.BeginEdit(false); grid.Rows.First.Focus() } – Rik May 20 '15 at 06:42
  • Are you sure is this valid grid.Rows.First.Focus()? there is no such method its showing – Mahrukh Mehmood May 20 '15 at 06:47
  • You are correct. So an entire row is not focusable. But isn't your grid.BeginEdit(false) not unfocussing? When I read https://msdn.microsoft.com/en-us/library/system.windows.forms.datagrid.beginedit%28v=vs.110%29.aspx it kind of suggest that. try removing that line, and see if it will focus. – Rik May 20 '15 at 06:52
  • I added this line after seeing somewhere on similar post, removed the line but no use – Mahrukh Mehmood May 20 '15 at 06:56
  • According to MSDN, setting the grid.BeginEdit(colStyle,row) should set focus, and put the grid in edit state. grid.BeginEdit(grid.TableStyles[0].GridColumnStyles[1],0) might give you the wanted result. Sorry, Ihave now sample project to try myself. – Rik May 20 '15 at 07:03
  • Its datagridview control, there is no overload method for BeginEdi(), it can have only bool value – Mahrukh Mehmood May 20 '15 at 07:09
  • I have been trying to reproduce, and it works for me with your code. Try setting BeginEdit to true. When you hit refresh, and then press tab, it should select the next cel in the first row. Else try to debug, and see if anything is executed after your btnRefresh_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) that removes focus. – Rik May 20 '15 at 07:51