[英]How do I get the previously selected cell in a DataGridView cell click event
[英]How do I click on a Cell of a DataGridView programmatically?
我有一個datagridview_cellclick方法,當我單擊一個單元格時,它會將dataGridView中的所有內容都放入變量中。 所以那沒問題。
但是我在放樣時想自動單擊同一DataGridView的第一個單元格。 不是自己用鼠標單擊,而是像程序在創建帶有dataGridView的表單時單擊第一個單元格本身。
這次單擊將調用上面的方法,因此即使我沒有單擊第一個單元格也可以設置變量。 我不確定是否清楚。 我怎樣才能做到這一點?
假設使用Windows窗體
漂亮的天真方法是調用具有所需參數集的函數:
dataGridView1_CellClick(this.dataGridView1, new DataGridViewCellEventArgs(0, 0));
盡管我不確定您在CellClickEvent中正在做什么,因為這會改變您想要訪問單元格的方式(或對該單元格執行某些操作)。 為了完整起見,我做了什么:
public Form1()
{
InitializeComponent();
dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
dataGridView1_CellClick(this.dataGridView1, new DataGridViewCellEventArgs(0, 0));
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("" + e.ColumnIndex + e.RowIndex);
}
將datagridview_cellclick
中的邏輯重構為一個單獨的函數,然后使用DataGridView.CurrentCell
設置單元格焦點。 您可以在Form_Load
設置
if (DataGridView.Rows.Count >= 0)
{
// Set the first cell
DataGridView.CurrentCell = DataGridView.Rows(0).Cells(0);
// Cell logic
UserSelectedCell(DataGridView.CurrentCell);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.