每当用户单击“添加到购物车”时,我将用户在“找到的项目”网格(屏幕截图的左侧)中选择的那些行添加到“选择的项目”网格(屏幕截图的右侧)按钮。
屏幕截图:link http://img856.imageshack.us/img856/3015/datagridview.jpg .
搜索按钮从搜索服务中获取图书列表。 我在 itemsFoundList 中显示的是 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)。
private void addToCart_Click( object sender, EventArgs e ) {
//I am not getting what to write here.
}
最佳答案
首先,您可能希望将 DataGridView 的 SelectionMode 更改为 FullRowSelect。否则用户可能会选择单元格而不是行,下面的代码将无法运行。 [尽管您可以对 Selected Cells 做类似的事情]
然后您需要从类似于以下的代码开始:
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 作为隐藏列返回,以便在您处理用户的购物车时它最终可用。
如果您想将项从一个 DataGridViewRow 移动到另一个 [以便它们一次只能存在于一个列表中],您可以这样做。
foreach (DataGridViewRow r in dataGridView1.SelectedRows)
{
dataGridView1.Rows.Remove(r);
dataGridView2.Rows.Add(r);
}
关于c# - 从 DataGridView 中获取选定的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5280655/