【问题标题】:Selecting rows programmatically in DataGridView在 DataGridView 中以编程方式选择行
【发布时间】:2013-01-29 06:18:38
【问题描述】:

我想在某些事件之后选择之前选择的行,我的代码如下。

int currentRow = dgvIcbSubsInfo.CurrentCell.RowIndex;
//code to execute
dgvIcbSubsInfo.Rows[currentRow].Selected = true;

执行代码后,预览将如下所示。但我需要在 id = 1272741(蓝色选择)中而不是在 1272737 中获得符号 >

【问题讨论】:

  • 哥们,这个问题很难理解,不够清楚!
  • > 表示第一行的选择箭头
  • 问题是选中项的行索引发生了变化(例如排序或重新查询数据源后)。

标签: c# .net visual-studio-2010 datagridview


【解决方案1】:

您可能已经看过DataGridView.CurrentRow Property,这是一个只读属性:

获取包含当前单元格的行。

但在备注部分,却写着:

要更改当前行,您必须将CurrentCell 属性设置为 所需行中的单元格。

另外,从DataGridView.CurrentCell Property,我们发现:

当你改变这个属性的值时,SelectionChanged 事件 发生在 CurrentCellChanged 事件之前。任何 SelectionChanged 事件 此时访问 CurrentCell 属性的处理程序将获得其 以前的值。

因此,您无需实际选择currentRow,因为当您设置CurrentCell 值时它将被选中(除非您有一些代码要在SelectionChanged 和@ 之间的当前范围内执行987654328@ 事件)。试试这个:

//dgvIcbSubsInfo.Rows[currentRow].Selected = true;
dgvIcbSubsInfo.CurrentCell = dgvIcbSubsInfo.Rows[currentRow].Cells[0];

【讨论】:

  • 这是对代码和 cmets 的非常好的挖掘,以及对您如何获得答案的详尽解释。谢谢亚历克斯!
【解决方案2】:

我认为您希望突出显示该行。请尝试以下代码,我认为它可能会有所帮助:

Color color = dgv.Rows[prevRowIndex].DefaultCellStyle.SelectionBackColor;
dgv.Rows[curRowIndex].DefaultCellStyle.SelectionBackColor = color;

【讨论】:

    【解决方案3】:

    尝试以下操作来更改当前行。由于 OP 不太清楚哪一行应该是新行,我的示例只是显示从当前行移动到上一行(如果有前一行)。第一行代码是可选的。如果您不想使用 FullRowSelect,也可以将 col 硬编码为 0(或其他列)以使用固定列。

    dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    int row = dataGridView.CurrentCell.RowIndex;
    int firstRow = dataGridView.Rows.GetFirstRow(DataGridViewElementStates.None);
    if (row != firstRow)
    {
      row--;
      int col = dataGridView.CurrentCell.ColumnIndex;
      dataGridView.CurrentCell = dataGridView[col, row];
    }
    

    【讨论】:

      【解决方案4】:

      我来到这里是想学习如何以编程方式选择 DataGridView 控件中的行。以下是如何在名为 dg1 的 DataGridView 控件中选择顶行并“单击”它:

      dg1.Rows[0].Selected = true;                      
      
      dg1_RowHeaderMouseClick(null, null);
      

      然后这会调用以下事件,该事件需要一个选定的行。

      private void dg1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
          {                        
              var selectedRows = dg1.SelectedRows;
      
              // Make sure we have a single row selected
              int count = selectedRows.Count;
      
              if (count == 1)
              {                
                  tbAssemblyName.Text = dg1.SelectedRows[0].Cells[0].Value.ToString();                
              }
          }
      

      当用户单击他们想要的行时,我一切正常。当只有一条记录可供选择时,我想为用户“点击”它。

      【讨论】:

        猜你喜欢
        • 2011-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-01
        • 1970-01-01
        • 2011-10-19
        • 2011-01-03
        相关资源
        最近更新 更多