【问题标题】:Datagridview Headers SelectionDatagridview 标题选择
【发布时间】:2020-07-06 12:57:35
【问题描述】:

我有一个包含 5 列的 DataGridView,当用户在任何标题上进行选择时,我想获得被选择的列索引,但我似乎正在获得被选择的当前单元格。

private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{

    dataGridView1.ClearSelection();

   //The e.RowIndex returns a -1 every time **`strong text`**
   // dataGridView1.Rows[e.RowIndex].Cells[1].Selected = true;

    var cellId = dataGridView1.CurrentCell.ColumnIndex;

    string column = dataGridView1.Columns[cellId].HeaderText;

    if (column == "Description")
    {
        dataGridView1.DataSource = notifications.OrderBy(a => a.Description).ToList();
    }
    else if (column == "Category")
    {
        dataGridView1.DataSource = notifications.OrderBy(a => a.Category).ToList();
    }
}

【问题讨论】:

  • 我不确定您在寻找什么。当用户单击列标题时,e.RowIndex 将返回 -1,但 e.ColumnIndex 应返回选定的列索引,因此不清楚您在问什么。

标签: c# datagridview controls


【解决方案1】:

使用e.ColumnIndex获取选中的ColumnIndex

 string column = dataGridView1.Columns[e.ColumnIndex].HeaderText;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多