Search code examples
c#winformsdatagridviewcolumn

How to get Columns in DataGridViewRowSelectedRowCollection


Ok guys, I thought this would be easier than it is.

 public static DataRowCollection ToRows(this DataGridViewSelectedRowCollection Rows)
 {
     DataTable table = new DataTable();            

     foreach (DataColumn column in Rows[0].DataGridView.Columns)
     {
         table.Columns.Add(column);
     }

     foreach (DataGridViewRow row in Rows)
     {
         DataRow newRow = ((DataRowView)row.DataBoundItem).Row;
         table.ImportRow(newRow);
     }

     return table.Rows;
}

I'm trying to get the columns of a row in a DataGridViewSelectedRowCollection. The code above throws an InvalidCast error on the table.Columns.Add(column) because it is trying to cast DataGridViewColumns to DataTable columns. I dont have access to the DataGridView because I am in a static method that Extends the DataGridViewSelectedRowCollection and do not have access to the DataGridView.

How can I cast the columns collection to a DataColumns object?


Solution

  • You can create an extension method to return the data rows behind selected rows of grid this way:

    public static class DataGridViewExtensions
    {
        public static List<DataRow> ToDataRows(this DataGridViewSelectedRowCollection Rows)
        {
            if (Rows == null || Rows.Count == 0)
                return null;
    
            return Rows.Cast<DataGridViewRow>()
                       .Where(x => x.DataBoundItem is DataRowView)
                       .Select(x => ((DataRowView)(x.DataBoundItem)).Row).ToList();
        }
    }
    

    Then to get values from a row variable of type DataRow, consider using these options:

    • row.ItemArray contains all column values
    • row[index] gets the value of a column by index
    • row["column name"] gets the value of column by column name
    • row.Table.Columns contains a list of columns of DataTable