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 determine which rows are selected in a DataGrid?

You could derive a control from DataGrid and add a SelectedItems property, along the lines of ListView.SelectedItems, like this:

using System.Collections;
using System.Data;
using System.Windows.Forms;

public class DataGridSelectedItems : DataGrid
{
  public IList SelectedItems
  {
    get
    {
      CurrencyManager cm = (CurrencyManager) BindingContext[ DataSource ];
      DataView dataView = (DataView) cm.List;

      ArrayList rows = new ArrayList();
      for ( int row = 0; row < dataView.Count; ++row )
        if ( IsSelected( row ) )
          rows.Add( row );

      return rows;
    }
  }
}

Download a working sample DataGridSelectedItems (C#, VB).

This doesn't scale well to large numbers of rows. For those situations, you could track the selections by monitoring keyboard and mouse actions, which would be more work.

George Shepherd, Syncfusion; John Hughes; Pieter Jansen van Vuuren; and Stuart Celarier, Fern Creek



Page view counter