Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

5. Windows Forms Datagrid

5.50 When I click on a row header, the row is selected and no cell is active. How can I do this programmatically?


This code adds a method to a derived grid that simulates a mouseclick on the rowheader of the row passed into the method.

     public class MyDataGrid : DataGrid
     {
               
          public const int WM_LBUTTONDOWN = 513; // 0x0201
          public const int WM_LBUTTONUP = 514; // 0x0202
          
          [System.Runtime.InteropServices.DllImport("user32.dll")]
          static extern bool SendMessage(IntPtr hWnd, Int32 msg, Int32 wParam, Int32 lParam);

          public void ClickRowHeader(int row)
          {
               //get a point to click
               Rectangle rect = this.GetCellBounds(row, 0);
               Int32 lparam = MakeLong(rect.Left - 4, rect.Top + 4);
          
               //clickit
               SendMessage( this.Handle, WM_LBUTTONDOWN, 0, lparam);
               SendMessage( this.Handle, WM_LBUTTONUP, 0, lparam);
          }

          static int MakeLong(int LoWord, int HiWord)
          {
               return (HiWord << 16) | (LoWord & 0xffff);
          }
          
     }
.....
.....
     //usage - myDataGrid is of type MyDataGrid.
     private void button2_Click(object sender, System.EventArgs e)
     {
          myDataGrid.ClickRowHeader(2);
     }