【问题标题】:How to programmatically set focus on a row in a WinForms DataGrid when selecting it?选择时如何以编程方式将焦点设置在 WinForms DataGrid 中的一行上?
【发布时间】:2021-06-13 06:37:04
【问题描述】:

我有一个 WinForms DataGrid(不是 DataGridView)。当我手动选择一行时,下面第一张图片中显示的行指示器显示在选定的行上。但是,如果我在保存后设置 DataGrid 的数据源并使用以下方式以编程方式选择第二行: datagrid.Select(1),第二行获得突出显示的背景颜色,但焦点指示器位于第一行,如下图第二张所示。

有没有办法让选定的行获得焦点并显示该行的指示器?

【问题讨论】:

    标签: c# winforms datagrid


    【解决方案1】:

    由于这是旧的System.Windows.Forms.DataGrid,因此行选择方法与 DataGridView 的略有不同。

    您可以使用Select() 方法选择行。
    这不会更改当前行。要使行成为当前行,您可以使用CurrentRowIndex 属性。
    结合起来,这两个移动选择并设置当前行。

     // Selects and highlights the Row at index 1
     dataGrid.Select(1);
     // Make the Row at index 1 the Current
     dataGrid.CurrentRowIndex = 1;
    

    DataGridView 中的类似内容:
    (可用于实现此结果的方法之一)

    // Move the focus and selects the Row at index 1
    dataGridView.Rows[1].Selected = true;
    // Make the Row at index 1 the Current setting the CurrentCell property
    dataGridView.CurrentCell = dgvTest.Rows[1].Cells[0];
    

    【讨论】:

      猜你喜欢
      • 2021-03-15
      • 2020-02-15
      • 2020-07-20
      • 2019-05-04
      • 1970-01-01
      • 2011-11-25
      • 2021-01-19
      • 1970-01-01
      • 2012-10-23
      相关资源
      最近更新 更多