按当前显示顺序获取选定的DataGridViewRows

问题描述 投票:0回答:7

我有一个带有未绑定数据的

DataGridView
,其中包含三个不同的
DataColumns
。行可以按每列排序,但除此之外不允许对显示的数据进行任何操作。

当我查询

SelectedRows
属性时,行按照我最初插入的顺序排序,而不是像我预期的当前显示或选择的顺序。有没有办法改变这种行为?

c# winforms datagridview
7个回答
10
投票

我也有同样的问题。 它看起来是最短路线:

List<DataGridViewRow> rows = 
    (from DataGridViewRow row in dgv.SelectedRows 
    where !row.IsNewRow 
    orderby row.Index 
    select row).ToList<DataGridViewRow>();

6
投票

SelectedRows 属性包含选定的行,但顺序相反,并且最新的项目位于列表的开头。要获得正确的用户选择的订单,请执行以下代码:

List<DataGridViewRow> dgList = new List<DataGridViewRow>();
foreach (DataGridViewRow r in dgv.SelectedRows)
{
    dgList.Insert(0, r);
}
foreach(DataGridViewRow r in dgList)
{
   //Print/consume your row here.
   int selectedIndex = r.Index;
}

注意:无需排序。


2
投票

我认为没有一种单行方法可以做到这一点。您需要将排序重新排序到您自己的列表中,然后将 IndexOf 与 SelectedItems 一起使用来找出视觉位置。

List<DataGridViewRow> l = new List<DataGridViewRow>();
foreach (DataGridViewRow r in dgv.Rows)
{
    l.Add(r);
}

l.Sort((x, y) =>
    {
        IComparable yComparable = (IComparable)x.Cells[dgv.SortedColumn.Index].Value;
        IComparable yc = (IComparable)x.Cells[dgv.SortedColumn.Index].Value;

        if (dgv.SortOrder == SortOrder.Ascending)
            return yc.CompareTo(yComparable);
        else
            return yComparable.CompareTo(yc);
    }
    );

foreach(DataGridViewRow r in dgv.SelectedRows)
{
    int selectedIndex = l.IndexOf(r);
}

请注意,上述内容尚未经过编译测试,可能需要一些调整。


2
投票

这是上述代码的 vb.net 版本。

C#

List<DataGridViewRow> rows = 
    (from DataGridViewRow row in dgv.SelectedRows 
    where !row.IsNewRow 
    orderby row.Index 
    select row).ToList<DataGridViewRow>();

VB.NET

Dim rows As List(Of DataGridViewRow) = (From row As DataGridViewRow 
   In dgv.SelectedRows Where Not row.IsNewRow Order By row.Index).ToList()

C# 到 VB.NET 转换器无法正确转换此内容。

希望这对任何希望使用它的 VB.NET 编码人员有所帮助。

保罗


0
投票

您应该能够像这样引用所选单元格中的值:

Private Sub determinePKVals(ByRef PKVal As String, ByRef PKVal2 As String, Optional ByVal row As Integer = -1)
    If row = -1 Then        ' optional value not passed
        row = dgvDisplaySet.CurrentRow.Index
    End If

    PKVal = dgvDisplaySet.Rows(row).Cells(0).Value
    PKVal2 = dgvDisplaySet.Rows(row).Cells(1).Value
End Sub

0
投票

SelectedCells 似乎按点击顺序或至少是相反的。这个工作原理尽可能简单:

foreach (DataGridViewRow row in dataGridLog.Rows)
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        if (cell.Selected)
            sb.AppendLine($"{cell.Value.ToString()}");
    }
}

0
投票

否则:

        List<DataGridViewRow> rows =
        [
            .. (from DataGridViewRow row in dgv.SelectedRows
                where !row.IsNewRow
                orderby row.Cells["some_column"].Value.ToString() ascending
            select row),
        ];

        foreach (DataGridViewRow dr in rows)
        {
        ...
        }
© www.soinside.com 2019 - 2024. All rights reserved.