从DataGridView获取所选的行 [英] 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.
屏幕截图:链接http://img856.imageshack.us/img856/3015/datagridview.jpg 。
搜索按钮带来了搜索中的图书列表服务。
我在itemFoundList中显示的是DataGridView。
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 );
}
现在我没有得到如何将所选行添加到cartList(这是一个DataGridView)。
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.
}
推荐答案
要将DataGridView的SelectionMode更改为FullRowSelect。否则,用户可能会选择单元格而不是行,下面的代码将不起作用。 [虽然你可以选择类似的选定单元格]
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
}
我个人将将bookid作为隐藏列返回,以便在处理用户的购物车时可用。
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.
如果您想将项目从一个DataGridViewRow移动到另一个[这样它们一次只能存在于一个列表中]可以这样做。
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);
}
这篇关于从DataGridView获取所选的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!