DataGridView.SelectedRows 属性

定义

获取用户选定的行的集合。

C#
[System.ComponentModel.Browsable(false)]
public System.Windows.Forms.DataGridViewSelectedRowCollection SelectedRows { get; }

属性值

一个 DataGridViewSelectedRowCollection,包含用户选定的行。

属性

示例

下面的代码示例演示如何在 UserDeletingRow 事件中使用 SelectedRows 属性。 在此示例中,如果集合中包含 SelectedRows 第一行,则取消删除。 此示例是 事件中提供的更大示例的 SelectionChanged 一部分。

C#
private void DataGridView1_UserDeletingRow(object sender,
    DataGridViewRowCancelEventArgs e)
{
    DataGridViewRow startingBalanceRow = DataGridView1.Rows[0];

    // Check if the Starting Balance row is included in the selected rows
    if (DataGridView1.SelectedRows.Contains(startingBalanceRow))
    {
        // Do not allow the user to delete the Starting Balance row.
        MessageBox.Show("Cannot delete Starting Balance row!");

        // Cancel the deletion if the Starting Balance row is included.
        e.Cancel = true;
    }
}

注解

属性 SelectionMode 必须设置为 FullRowSelectRowHeaderSelect ,才能 SelectedRows 使用所选行填充属性。

此属性包含引用所选内容的只读快照。 如果保留此集合的副本,它可能与用户更改所选内容的实际后续 DataGridView 状态不同。 因此,不应对集合的副本进行操作。

若要以编程方式选择行,请将其 Selected 属性设置为 true

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅