DataGridView.SelectedColumns 属性

定义

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

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

属性值

DataGridViewSelectedColumnCollection

一个 DataGridViewSelectedColumnCollection,表示用户选定的列。

属性

示例

下面的代码示例演示如何使用 SelectedColumns 属性在编程排序中获取所选列。 在此示例中,此方法使用 Sort 此属性来确定排序的方向。

C#
private void sortButton_Click(object sender, System.EventArgs e)
{
    // Check which column is selected, otherwise set NewColumn to null.
    DataGridViewColumn newColumn =
        dataGridView1.Columns.GetColumnCount(
        DataGridViewElementStates.Selected) == 1 ?
        dataGridView1.SelectedColumns[0] : null;

    DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
    ListSortDirection direction;

    // If oldColumn is null, then the DataGridView is not currently sorted.
    if (oldColumn != null)
    {
        // Sort the same column again, reversing the SortOrder.
        if (oldColumn == newColumn &&
            dataGridView1.SortOrder == SortOrder.Ascending)
        {
            direction = ListSortDirection.Descending;
        }
        else
        {
            // Sort a new column and remove the old SortGlyph.
            direction = ListSortDirection.Ascending;
            oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
        }
    }
    else
    {
        direction = ListSortDirection.Ascending;
    }

    // If no column has been selected, display an error dialog  box.
    if (newColumn == null)
    {
        MessageBox.Show("Select a single column and try again.",
            "Error: Invalid Selection", MessageBoxButtons.OK,
            MessageBoxIcon.Error);
    }
    else
    {
        dataGridView1.Sort(newColumn, direction);
        newColumn.HeaderCell.SortGlyphDirection =
            direction == ListSortDirection.Ascending ?
            SortOrder.Ascending : SortOrder.Descending;
    }
}

注解

属性 SelectionMode 必须设置为 DataGridViewSelectionMode.FullColumnSelectDataGridViewSelectionMode.ColumnHeaderSelectSelectedColumns 填充所选列的属性。

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

适用于

产品 版本
.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
Windows Desktop 3.0, 3.1, 5, 6, 7

另请参阅