【问题标题】:Get the selected Rows from a DataGridView从 DataGridView 中获取选定的行
【发布时间】:2011-03-12 04:56:52
【问题描述】:

每当用户单击“添加到购物车”时,我都会将用户在“找到的项目”网格(屏幕截图的左侧)中选择的那些行添加到“已选择的项目”网格(屏幕截图的右侧)按钮。

屏幕截图:link http://img856.imageshack.us/img856/3015/datagridview.jpg

搜索按钮从搜索服务中提供图书列表。 我在作为 DataGridView 的 itemsFoundList 中显示。

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.
}

【问题讨论】:

  • 您可以控制 searchServiceClient 吗?还是第三方维护的服务?
  • 除了您现在返回的信息之外,假设您可能还有一个 BookID 或另一个可以返回的唯一标识符是否安全?
  • 是的。如果您愿意,我们可以返回唯一标识符。但是这有什么关系呢?我只希望用户选择的那些行能够显示在另一个网格中。

标签: c# winforms datagridview


【解决方案1】:

首先,您可能希望将 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);
}

【讨论】:

  • "首先,您可能希望将 DataGridView 的 SelectionMode 更改为 FullRowSelect。" - 成就了我的一天。 :-)
  • 哈,这是一个有趣的小错字,希望对你有用。
猜你喜欢
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
相关资源
最近更新 更多