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 find the top-left visible cell in a DataGrid?

In a Windows Forms DataGrid, there is no property exposed that gives you this information. But here is little trick that will allow you to get the top-left visible cell.

1) Add a private member Point pointInCell00 to the form containing the DataGrid.

2) After the DataGrid has been initialized, but before your user has been able to scroll it (say at the end of the Form_Load event), use code such as this to initialize pointInCell00 to be a point in cell 0,0.

pointInCell00 = new Point( dataGrid1.GetCellBounds(0,0).X + 4,
  dataGrid1.GetCellBounds(0,0).Y + 4 );

3) Then add this method to return DataGridCell that is the top-left cell.

public DataGridCell TopLeftVisibleCell()
{
  DataGrid.HitTestInfo hti = dataGrid1.HitTest( pointInCell00 );
  return new DataGridCell( hti.Row, hti.Column );
}

Sample usage:

private void button1_Click(object sender, EventArgs e)
{
  DataGridCell dgc = TopLeftVisibleCell();
  MessageBox.Show( dgc.RowNumber.ToString() + " " +
    dgc.ColumnNumber.ToString() );
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter