CareTaker22
CareTaker22

Reputation: 1300

Copying all rows from one DataGrid to another

I'm trying to copy all the selected rows from one datagrid to another. Here is what i've been trying to do so far:

private void btnFeedbackSelectSupplier_Click(object sender, RoutedEventArgs e)
{
    dgFeedbackAddCost.SelectAll();

    IList list = dgFeedbackAddCost.SelectedItems as IList;
    IEnumerable<ViewQuoteItemList> items = list.Cast<ViewQuoteItemList>();

    //Example of how I want to access the data from the first datagrid and add it to
    //the second one.
    var item = (new ViewQuoteItemList
    {
        Item = items.Item,
        Supplier = items.Cost
    });
    //Example

    dgFeedbackSelectSupplier.Items.Add(item);
}

My issue is here:

var item = (new ViewQuoteItemList
{
    Item = items.Item,
    Supplier = items.Cost
});

And I'm getting the error:

'System.Collections.Generic.IEnumerable' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)

Now I know I'm doing it wrong, it's just I don't know how else I can show you what I want to achieve with the code snippets.

So my question is, how would I be able to access that data from the items cast and add it to my ViewQuoteItemList for my second datagrid?

Upvotes: 0

Views: 1577

Answers (2)

Takarii
Takarii

Reputation: 1648

This would satisfy your need to only add the selected rows to the datatable. Then you can merge 2 datatables if you just want to add them together - then rebind the source to the second grid.

DataTable dt = new DataTable();
foreach (DataGridViewColumn column in dataGridView1.Columns)
    dt.Columns.Add(column.Name, column.CellType);
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
     dt.Rows.Add();
     for (int j = 0; j < dataGridView1.Columns.Count; j++)
     {
         dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;

     }
 }

Reference Here

Upvotes: 1

Ian
Ian

Reputation: 30813

You could get all the new items using LINQ:

var items2 = (from i in items
           let a = new ViewQuoteItemList { Item = i.Item, Supplier = i.Cost }
           select a).ToList();

foreach(var item in items2)
    dgFeedbackSelectSupplier.Items.Add(item);

Upvotes: 2

Related Questions