2011-12-26 70 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 
相關問題