DataGridView.SelectedRows 属性

定义

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

public:
 property System::Windows::Forms::DataGridViewSelectedRowCollection ^ SelectedRows { System::Windows::Forms::DataGridViewSelectedRowCollection ^ get(); };
[System.ComponentModel.Browsable(false)]
public System.Windows.Forms.DataGridViewSelectedRowCollection SelectedRows { get; }
[<System.ComponentModel.Browsable(false)>]
member this.SelectedRows : System.Windows.Forms.DataGridViewSelectedRowCollection
Public ReadOnly Property SelectedRows As DataGridViewSelectedRowCollection

属性值

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

属性

示例

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

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;
    }
}
Private Sub UserDeletingRow(ByVal sender As Object, _
    ByVal e As DataGridViewRowCancelEventArgs) _
    Handles DataGridView1.UserDeletingRow

    Dim startingBalanceRow As DataGridViewRow = DataGridView1.Rows(0)

    ' Check if the starting balance row is included in the selected rows
    If DataGridView1.SelectedRows.Contains(startingBalanceRow) Then
        ' 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
    End If
End Sub

注解

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

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

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

适用于

另请参阅