George Shepherd's Windows Forms FAQ
Questions and answers in this FAQ have been collected from newsgroup posts, various mailing lists and the employees of Syncfusion.

5.20 How do I programmatically determine the selected rows in a datagrid


The method DataGrid.IsSelected can tell you if a particular row is selected. So, you could use IsSelected in a loop through all your rows to finds if multiple rows have been selected. Depending upon the size of your datagrid, this may be a viable solution. If not, you could track the selections yourself by monitoring the key actions and the mouse actions. This would be more work. Thanks to John Hughes to the suggestion to use the dataview.

[C#]
public ArrayList GetSelectedRows(DataGrid dg)
{
     ArrayList al = new ArrayList();
     CurrencyManager cm = (CurrencyManager)this.BindingContext[dg.DataSource, dg.DataMember];
     DataView dv = (DataView)cm.List;

     for(int i = 0; i < dv.Count; ++i)
     {
          if(dg.IsSelected(i))
               al.Add(i);
     }
     return al;
}

private void button1_Click(object sender, System.EventArgs e)
{
     string s = "Selected rows:";
     foreach(object o in GetSelectedRows(dataGrid1))
     {
          s+=""+o.ToString();
     }
     MessageBox.Show(s);
}

[VB.NET]
     Public Function GetSelectedRows(ByVal dg As DataGrid) As System.Collections.ArrayList
          Dim al As New ArrayList()

          Dim cm As CurrencyManager = Me.BindingContext(dg.DataSource, dg.DataMember)
          Dim dv As DataView = CType(cm.List, DataView)

          Dim i As Integer
          For i = 0 to dv.Count - 1
               If dg.IsSelected(i) Then
                    al.Add(i)
               End If
          End Next
          Return al
     End Function 'GetSelectedRows
     
      Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
           Dim s As String = "Selected rows:"
          Dim o As Object
          For Each o In GetSelectedRows(dataGrid1)
               s += " " + o.ToString()
          Next o
          MessageBox.Show(s)
      End Sub 'button1_Click


Windows Forms-Datagrid

© 2001-2010 Copyright Syncfusion Inc. All rights reserved.  |  Privacy Policy  |  Contact  |  Sitemap