简体   繁体   English

以编程方式在 DataGridView 中选择一行

[英]Selecting a row in DataGridView programmatically

How can I select a particular range of rows in a DataGridView programmatically at runtime?如何在运行时以编程方式 select DataGridView中的特定行范围?

Not tested, but I think you can do the following:未经测试,但我认为您可以执行以下操作:

dataGrid.Rows[index].Selected = true;

or you could do the following (but again: not tested):或者您可以执行以下操作(但再次:未测试):

dataGrid.SelectedRows.Clear();
foreach(DataGridViewRow row in dataGrid.Rows)
{
    if(YOUR CONDITION)
       row.Selected = true;
}

In Visual Basic, do this to select a row in a DataGridView ;在 Visual Basic 中,对 select 在DataGridView中的一行执行此操作; the selected row will appear with a highlighted color but note that the cursor position will not change:所选行将以突出显示的颜色显示,但请注意 cursor position 不会改变:

Grid.Rows(0).Selected = True

Do this change the position of the cursor:执行此更改 cursor 的 position:

Grid.CurrentCell = Grid.Rows(0).Cells(0)

Combining the lines above will position the cursor and select a row.结合上面的行将 position cursor 和 select 一行。 This is the standard procedure for focusing and selecting a row in a DataGridView :这是在DataGridView中聚焦和选择一行的标准过程:

Grid.CurrentCell = Grid.Rows(0).Cells(0)
Grid.Rows(0).Selected = True
DataGridView.Rows
    .OfType<DataGridViewRow>()
     .Where(x => (int)x.Cells["Id"].Value == pId)
     .ToArray<DataGridViewRow>()[0]
     .Selected = true;
 <GridViewName>.ClearSelection(); ----------------------------------------------------1
 foreach(var item in itemList) -------------------------------------------------------2
 {
    rowHandle =<GridViewName>.LocateByValue("UniqueProperty_Name", item.unique_id );--3
    if (rowHandle != GridControl.InvalidRowHandle)------------------------------------4
    {
        <GridViewName>.SelectRow(rowHandle);------------------------------------ -----5
    }
  }
  1. Clear all previous selection.清除所有先前的选择。
  2. Loop through rows needed to be selected in your grid.循环遍历需要在网格中选择的行。
  3. Get their row handles from grid (Note here grid is already updated with new rows)从网格获取他们的行句柄(注意这里的网格已经用新行更新)
  4. Checking if the row handle is valid or not.检查行句柄是否有效。
  5. When valid row handle then select it.当有效的行句柄然后 select 它。

Where itemList is list of rows to be selected in the grid view.其中 itemList 是要在网格视图中选择的行列表。

Try This:尝试这个:

datagridview.Rows[currentRow].Cells[0];

You can use the Select method if you have a datasource: http://msdn.microsoft.com/en-us/library/b51xae2y%28v=vs.71%29.aspx如果您有数据源,则可以使用 Select 方法: http://msdn.microsoft.com/en-us/library/b51xae2y%28v=vs.71%29.aspx

Or use linq if you have objects in you datasource如果数据源中有对象,或者使用 linq

Try this:尝试这个:

DataGridViewRow row = dataGridView1.Rows[index row you want];
dataGridView1.CurrentRow = row;

Hope this help!希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM