0

I am trying to move selected rows from one DGV to another DGV at the click of a button.

I really don't know where to begin..

I have two seperate DGVs that are bound by a DataSource..

choiceDGV.DataSource = theChoiceList;
universalDGV.DataSource = theUniversalList;

I would like to move any selected items in the choiceDGV to the univeralDGV by a click of a button. I need to make sure the selected rows are removed from the one DGV and added to the 2nd DGV.

Both of the DataGridView's have the same amount of columns.

theNoobGuy
  • 1,636
  • 6
  • 29
  • 45

2 Answers2

2

Did you try:

foreach (DataGridViewRow row in choiceDGV.SelectedRows)
{
     universalDGV.Rows.Add(row);
     choiceDGV.Rows.Delete(row);
}

or (edited: DataGridViewRow doesn't have ItemArray unfortunately):

foreach (DataGridViewRow row in choiceDGV.SelectedRows)
{
     object[] items = new object [row.Cells.Count];
     for (int i = 0; i < row.Cells.Count; i++)
         items[i] = row.Cells[i].Value;
     universalDGV.Rows.Add(items);
     choiceDGV.Rows.Delete(row);
}
slawekwin
  • 6,270
  • 1
  • 44
  • 57
  • I have tried doing this and the logic seems like it would work.. it just isnt moving anything. I am wondering why it doesn't.. hmm – theNoobGuy Aug 25 '11 at 16:11
  • I figured out I needed to have the entire row selected when clicking on a single cell. I used this [link](http://stackoverflow.com/questions/285829/datagridview-how-to-focus-the-whole-row-instead-of-a-single-cell) to do that. So now my error that I am getting is: `Rows cannot be programmatically added to the DataGridView's rows colletion when the control is data-bound.` – theNoobGuy Aug 25 '11 at 17:52
  • I looked at your comment in other answer and found what is the type of data in your datasource, so I would try to do sth like: theUniversalList.Add(new LoadLine(items[0], items[1], .../*or any form your LoadLine constructor accepts*/)); instead of universalDGV.Rows.Add(items); Then theUniversalList.EndEdit() (not sure if it is actually needed) and rebind DGV. Hope that helps – slawekwin Aug 25 '11 at 18:24
  • Okay that makes sense. But how do I get the `items[0], items[1], ...` from the other DGV? – theNoobGuy Aug 25 '11 at 18:32
  • as I did in my original answer: for (int i = 0; i < row.Cells.Count; i++) items[i] = row.Cells[i].Value; – slawekwin Aug 25 '11 at 18:37
1

I can't see the issue. You just need move the items you like to the UniversalList within the onclick button handler and call .DataBind() on both the datagridview. In other words you have to hit the lists(datasource) instead of the data grid view

Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70