Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the selected Rows from a DataGridView

I am adding those rows which are selected by user in "Items Found" grid ( left hand side of screen shot) to "Items selected" grid ( right hand side of screen shot) whenever the user clicks "Add To Cart" button.

The screen shot: link http://img856.imageshack.us/img856/3015/datagridview.jpg.

The Search Button brings the list of books from the Search Service. Which I display in itemsFoundList which is DataGridView.

private void searchButton_Click( object sender, EventArgs e )
{
    itemsFoundList.Columns.Clear ();
    string[] list = searchServiceClient.BookSearch ( getBookName.Text, getAuthorName.Text );
    itemsFoundList.Columns.Add ( "Items", "Items found:" );
    displayToGrid ( itemsFoundList, list );
}

Now I am not getting how to add the selected rows to cartList(which is a DataGridView).

private void addToCart_Click( object sender, EventArgs e ) {
    //I am not getting what to write here.
}
like image 839
ivorykoder Avatar asked Mar 12 '11 04:03

ivorykoder


Video Answer


1 Answers

First in you'll probably want to change the SelectionMode of your DataGridView to FullRowSelect. Otherwise users will likely select cells and not rows and the code below would not work. [Though you could do something similar with Selected Cells]

Then you'll want to start with code similar to the following:

foreach (DataGridViewRow r in dataGridView1.SelectedRows)
{
   //Code to add selected row to new datagrid.
   //Important to note that dataGridView2.Rows.Add(r) will not work 
   //because each row can only belong to one data grid.  You'll have 
   //to create a new Row with the same info for an exact copy
}

Personally I would return the bookid as a hidden column so that it ends up being available for when you are processing the user's cart.

If you wanted to move the items from one DataGridViewRow to the other [so that they could only exist in one list at a time] you could do this.

foreach (DataGridViewRow r in dataGridView1.SelectedRows)
{
  dataGridView1.Rows.Remove(r);
  dataGridView2.Rows.Add(r);
}
like image 117
iwalkbarefoot Avatar answered Oct 08 '22 07:10

iwalkbarefoot