如何获取 DataGridView 中所有选定单元格的值?

发布于 2024-08-16 11:45:07 字数 77 浏览 3 评论 0原文

我有一个具有 MultiSelect = true 的 DataGridView。用户从不同行选择不同单元格后,如何获取所有选定单元格的值?

I have a DataGridView that has MultiSelect = true. After the user selects different cells from different rows how can I get the value of all the selected cells?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乱了心跳 2024-08-23 11:45:07

您可以迭代 SelectedCells

foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
    MessageBox.Show(cell.Value.ToString());
}

您只要求提供值,但您可能还想知道单元格的行和列,否则该值可能毫无意义。您也可以在单元对象上访问这些。

You can iterate over SelectedCells.

foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
    MessageBox.Show(cell.Value.ToString());
}

You asked only for the value, but you probably also want to know the row and the column of the cell otherwise the value could be meaningless. You can access these also on the cell object.

静水深流 2024-08-23 11:45:07

foreach -

DataGrid.SelectedCells

有关 SelectedCells 属性的更多信息,请访问 http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectedcells.aspx

对于 DataGridView 中的大量选择,SelectedCells 集合效率低下。您可以使用一种方法来获取所选单元格的计数。在此基础上进行迭代,速度会更快。

for (int i = 0; i < grid.GetCellCount(System.Windows.Forms.DataGridViewElementStates.Selected); i++)
{
    string val = grid.SelectedCells[i].Value;
}

foreach -

DataGrid.SelectedCells

More info on the SelectedCells Property can be found at http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectedcells.aspx

The SelectedCells collection is inefficient with large selections in DataGridView. There is a method you can use to get the count of the selected cells. iterate based on that and it'll be faster.

for (int i = 0; i < grid.GetCellCount(System.Windows.Forms.DataGridViewElementStates.Selected); i++)
{
    string val = grid.SelectedCells[i].Value;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文