从一个DataGridView获取选定行 [英] Get the selected Rows from a DataGridView
问题描述
我加入这是由用户在发现项目网格(屏幕截图的左侧),选择那些行选择项,每当用户点击加入购物车网格(屏幕截图的右手边) 。按钮
该屏幕快照:
搜索按钮带来的从搜索服务书籍列表。
我在itemsFoundList显示这是DataGridView中。
私人无效searchButton_Click(对象发件人,EventArgs五)
{
itemsFoundList.Columns.Clear() ;
的String [] =名单searchServiceClient.BookSearch(getBookName.Text,getAuthorName.Text);
itemsFoundList.Columns.Add(项目,找到的项目:);
displayToGrid(itemsFoundList,清单);
}
现在我没有得到如何将所选行添加到cartList(这是一个DataGridView)。
私人无效addToCart_Click(对象发件人,EventArgs五){
//我没有得到什么就写到这里。
}
首先,在你可能会要改变你的DataGridView到FullRowSelect的的SelectionMode。否则,用户可能会选择单元格,而不是行和下面的代码是行不通的。 [虽然你可以做选定的单元格类似]
然后你将要开始的代码类似以下内容:
的foreach(在dataGridView1.SelectedRows的DataGridViewRow R)
{
//代码来添加选定行新的数据网格。
//需要注意的是dataGridView2.Rows.Add(R)将无法正常工作
//因为每行只能属于一个数据网格。您将有
//创建一个新的行为的精确副本
}
同样的信息
我个人将返回BOOKID为隐藏列,以便它结束了,当你处理用户的购物车为是可用的。
如果您想移动从一个的DataGridViewRow的项目其他的你可以做到这一点[,使他们能够在一个列表中一次只能存在。
的foreach(在dataGridView1.SelectedRows的DataGridViewRow R)
{
dataGridView1.Rows.Remove(R);
dataGridView2.Rows.Add(R);
}
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: .
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.
}
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);
}
这篇关于从一个DataGridView获取选定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!