2015-10-18 102 views
0

我試圖填充DataGridView並預選一個單元格。 但它運行不正常。 我使用此代碼創建DataGridViewDataGridView設置CurrentCell不起作用

DataTable table = new DataTable(); 
table.Columns.Add("Column1"); 
table.Columns.Add("Column2"); 
table.Rows.Add("Row1"); 
table.Rows.Add("Row2"); 
table.Rows.Add("Row3"); 
table.Rows.Add("Row3"); 
table.Rows.Add("Row4"); 
table.Rows.Add(""); 

dataGridView1.DataSource = table; 
dataGridView1.ReadOnly = false; 
dataGridView1.Columns["Column1"].ReadOnly = true; 
dataGridView1[1, 2].ReadOnly = true; 
dataGridView1[1, 3].ReadOnly = true; 

DataGridViewButtonCell button = new DataGridViewButtonCell(); 
dataGridView1[1, table.Rows.Count - 1] = button; 
button.Value = "Go"; 
button.FlatStyle = FlatStyle.Flat; 

dataGridView1.CurrentCell = dataGridView1[0, 1]; 

理論上右側第一個單元格應進行選擇,但在第1列第3行被選中。 難道這個問題,這導致:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e) 
{ 

} 

或者

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e) 
{ 

} 

回答

1

您使用以下

dataGridView1.CurrentCell = dataGridView1[0, 1]; 

理論上的第一個單元格上應選擇右側

事實上,單元格索引的參數r是columnIndex, rowIndex,所以上面應該選擇第二行的第一列,它的確如此。如果您打算選擇第一行的第二列,請使用dataGridView[1, 0]

+0

我測試過dataGridView1.CurrentCell = dataGridView1 [0,0]; 弼第二列和第二行被選中。 這就像他不知道第一行。 – ComanderKai77

+0

@ ComanderKai77何時執行上述方法 - 窗體構造函數,加載事件或? –

+0

在Form1_Load中,我使用此代碼調用方法。 – ComanderKai77

1

當你想設置dataGridView1.CurrentCell你應該注意,在dataGridView1[0, 1]第一個數字是columnIndex和第二個數字是rowIndex。所以,如果你想選擇右側的第一個單元格,你應該試試這個:

dataGridView1.CurrentCell = dataGridView1[1,0];//first row second column