Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I programmatically select a row in a DataGrid and have no cell active, just like when the user clicks on a row header?

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

using System.Runtime.InteropServices;

public class CustomDataGrid : DataGrid
{
  public const int WM_LBUTTONDOWN = 513; // 0x0201
  public const int WM_LBUTTONUP = 514; // 0x0202

  [ 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 = GetCellBounds( row, 0 );
    Int32 lparam = MakeLong( rect.Left - 4, rect.Top + 4 );

    // click it
    SendMessage( Handle, WM_LBUTTONDOWN, 0, lparam);
    SendMessage( Handle, WM_LBUTTONUP, 0, lparam);
  }

  static int MakeLong( int LoWord, int HiWord )
  {
    return (HiWord << 16) | (LoWord & 0xffff);
  }
}

Usage:

private DataGrid dataGrid1 = new CustomDataGrid();

// ...

private void button1_Click( object sender, EventArgs e )
{
  dataGrid1.ClickRowHeader(2);
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter