如何在数据网格/网格视图中设置特定行的焦点?

12

我有一个数据网格/网格视图。初始时,我将网格填充了10行。每次点击按钮后,我会不断地添加10行到数据网格/网格视图中。现在我想要每次填充网格时将焦点设置到最后一行。我可以获取该行的索引,但我无法将焦点设置到那行。

你们中有人知道如何在C #中实现吗?

7个回答

17

试一试

dataGridView1.ClearSelection();
int nRowIndex = dataGridView1.Rows.Count - 1;

dataGridView1.Rows[nRowIndex].Selected = true;
dataGridView1.Rows[nRowIndex].Cells[0].Selected = true;

朋友,我正在该按钮的单击事件中设置焦点。但是我找不到任何名为“Row”和“Selected”的网格视图属性。请告诉我如何获取它们。 - Sukanya
1
谢谢。我尝试了你的代码,但是它报错了,错误信息为“GridviewRow不包含名为'Selected'的定义,也没有接受类型为System.Web.UI.WebControls.GridViewRow的第一个参数的扩展方法'Selected'”。我是否缺少任何指令或程序集引用? - Sukanya

10

对于WinForms DataGridView:

myDataGridView.CurrentCell = myDataGridView.Rows[theRowIndex].Cells[0];

对于WebForms GridView,请使用SelectedIndex属性。

myGridView.SelectedIndex = theRowIndex;

@Sukanya,这里提到的是DataGridView。你是否在使用WebForm GridView?如果是,请在你的问题中标记一下。 - akoso
朋友,我正在使用.NET 4.0。我正在创建Web表单。我只得到了两个ASP网格,它们是DataGrid和GridView。对于这两个网格,我没有得到.CurrentCell属性。是我的问题吗?第二点是,我已经能够使用“SelectedIndex”将焦点设置到特定的行索引,但我的问题是我无法将焦点集中到该特定行。 - Sukanya

2

试一试...

DataGridViewRow rowToSelect = this.dgvJobList.CurrentRow;

rowToSelect.Selected = true;



rowToSelect.Cells[0].Selected = true;

this.dgvJobList.CurrentCell = rowToSelect.Cells[0];

this.dgvJobList.BeginEdit(true);

0

这篇文章真是太有用了。我正在使用Visual Studio 2017中的VB,只需要到DATAGRID的底部允许用户输入数据。通过研究这些答案,我想出了这个解决方案,并认为其他人可能会发现它有用。

Private Sub AddBUTTON_Click(sender As Object, e As RoutedEventArgs) Handles 
AddBUTTON.Click
        ' Go to bottom to allow user to add item in last row
        DataGrid.Focus()
        DataGrid.UnselectAll()
        DataGrid.SelectedIndex = 0
        DataGrid.ScrollIntoView(DataGrid.SelectedItem)
        Dim endofitems As Integer = DataGrid.Items.Count         
        DataGrid.ScrollIntoView(DataGrid.Items.GetItemAt(endofitems - 1))
    End Sub

0
在我的情况下,我有一个按钮,它可以向 datagridView1 添加新行,并激活新添加的行的第二个单元格 C# Windows Form 应用程序。
int rowIndex = datagridView1.Rows.Count - 1;
datagridView1.CurrentCell = datagridView1.Rows[rowIndex].Cells[1];
datagridView1.BeginEdit(false);

0

你可以试试这个,对我来说很有效

   public static void ItemSetFocus(DataGrid Dg, int SelIndex)
    {
        if (Dg.Items.Count >= 1 && SelIndex < Dg.Items.Count)
        {
           Dg.ScrollIntoView(Dg.Items.GetItemAt(SelIndex));
           Dg.SelectionMode = DataGridSelectionMode.Single;
           Dg.SelectionUnit = DataGridSelectionUnit.FullRow;
           Dg.SelectedIndex = SelIndex;
           DataGridRow row = (DataGridRow)Dg.ItemContainerGenerator.ContainerFromIndex(SelIndex);
                row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }

-1

尝试这个,在Extjs 4.2.0中,我与下面的脚本片段很好地配合使用。

//currentIndex is the index of grid row
var rowElement = this.getView().getRecord(currentIndex);
this.getView().focusRow(rowElement);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接