[英]How do I click on a Cell of a DataGridView programmatically?
I have a method datagridview_cellclick who does put everything from the dataGridView into variables when I click on a cell. 我有一个datagridview_cellclick方法,当我单击一个单元格时,它会将dataGridView中的所有内容都放入变量中。 So no problem there.
所以那没问题。
But i want to automatically click on the first cell of the same DataGridView when I lauch my program. 但是我在放样时想自动单击同一DataGridView的第一个单元格。 Not click by myself with the mouse, but like the program does click on the first cell itself when the form with the dataGridView is created.
不是自己用鼠标单击,而是像程序在创建带有dataGridView的表单时单击第一个单元格本身。
And this click would call the method above so I get the variables set even if I don't click on the first cell. 这次单击将调用上面的方法,因此即使我没有单击第一个单元格也可以设置变量。 I'm not sure if this clear.
我不确定是否清楚。 How can I do this?
我怎样才能做到这一点?
Assuming that Windows Forms are used 假设使用Windows窗体
Pretty Naive method is to call the function with required parameter's set: 漂亮的天真方法是调用具有所需参数集的函数:
dataGridView1_CellClick(this.dataGridView1, new DataGridViewCellEventArgs(0, 0));
Although I am not sure what you are doing in the CellClickEvent, because that can change the way you want to access the cell (or do something with that cell). 尽管我不确定您在CellClickEvent中正在做什么,因为这会改变您想要访问单元格的方式(或对该单元格执行某些操作)。 For completeness sake what i did:
为了完整起见,我做了什么:
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);
}
Refactor your logic in datagridview_cellclick
to a separate function, then use DataGridView.CurrentCell
to set cell focus. 将
datagridview_cellclick
中的逻辑重构为一个单独的函数,然后使用DataGridView.CurrentCell
设置单元格焦点。 You may set it in the Form_Load
您可以在
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.