2011-12-26 72 views
5

我有一个datagrid/gridview。我最初用10行填充网格。在每次点击按钮时,我都会继续向datagrid/gridview添加10行。现在我想在每次填充网格时将焦点设置到最后一行。我可以得到该行的索引,但我无法将焦点设置到该特定行。如何将焦点设置在datagrid/gridview中的特定行上?

你们中的任何人都有任何想法如何在C#中做到这一点?

回答

10

试试这个

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

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

朋友,我设置在该按钮的点击焦点event.And我找不到任何的GridView属性作为“行” and'.Selected'.Please告诉我怎样才能让他们.. – Sukanya 2011-12-26 12:49:29

+0

更新后检查 – 2011-12-26 12:59:11

+1

Thanks.I尝试了您的代码,但它给出了错误,因为“GridviewRow不包含'Selected'的定义,也没有接受System.Web.UI.WebControls类型的第一个参数的扩展方法'Selected'。 GridViewRow可以找到“。我缺少任何指令或程序集引用? – Sukanya 2011-12-26 13:05:36

1

尝试......

DataGridViewRow rowToSelect = this.dgvJobList.CurrentRow; 

rowToSelect.Selected = true; 



rowToSelect.Cells[0].Selected = true; 

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

this.dgvJobList.BeginEdit(true); 
+0

我没有得到任何财产作为.CurrentRow gridview.Please帮助.. – Sukanya 2011-12-26 12:50:17

4

对于的WinForms DataGridView的:

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

对于WebForms的GridView控件,使用SelectedIndex财产

myGridView.SelectedIndex = theRowIndex; 
+0

没有财产作为'CurrentCell'gridview .. – Sukanya 2011-12-26 13:07:24

+0

@Sukanya有[DataGridView](http://msdn.microsoft.com /en-us/library/system.windows.forms.datagridview.currentcell.aspx)。你在使用WebForm GridView吗?如果是,请在您的问题中标记。 – akoso 2011-12-26 13:14:15

+0

@Sukanya看看我的编辑 – akoso 2011-12-26 13:22:51

0

试试这个,我在Extjs 4.2.0中使用下面的脚本代码很好。

//currentIndex is the index of grid row 
var rowElement = this.getView().getRecord(currentIndex); 
this.getView().focusRow(rowElement); 
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)); 
     } 
    } 
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 
相关问题