How to set focus on a particular row in a datagrid/gridview?

こ雲淡風輕ζ 提交于 2019-12-19 02:02:31

问题


I have a datagrid/gridview. I'm populating the grid with 10 rows initially. On a button click every time,I'm keeping on adding 10 rows to the datagrid/gridview. Now I want to set the focus to the last row every time the grid is populated. I can get the index of that row,but I can't set focus to that particular row.

Do anyone of you have any idea how to do it in C#?


回答1:


Try this

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

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



回答2:


For WinForms DataGridView:

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

For WebForms GridView, use the SelectedIndex property

myGridView.SelectedIndex = theRowIndex;



回答3:


Try this...

DataGridViewRow rowToSelect = this.dgvJobList.CurrentRow;

rowToSelect.Selected = true;



rowToSelect.Cells[0].Selected = true;

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

this.dgvJobList.BeginEdit(true);



回答4:


Try this, it's work for me

   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));
        }
    }



回答5:


This post has been a god send. I am using VB in Visual Studio 2017 and just needed to go to the bottom of a DATAGRID to allow user to input data. By studying these answers I came up with this solution and thought others might find it useful.

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



回答6:


Try this, I'm works well with below script snippet in Extjs 4.2.0.

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


来源:https://stackoverflow.com/questions/8635731/how-to-set-focus-on-a-particular-row-in-a-datagrid-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!