如何在程序中编程点击DataGridView的单元格?

3
我有一个名为datagridview_cellclick的方法,当我单击单元格时,它会将所有内容放入变量中。这方面没有问题。
但是我想在启动程序时自动单击同一DataGridView的第一个单元格。不是通过鼠标手动单击,而是像程序在创建带有DataGridView的窗体时自己单击第一个单元格。
这个点击将调用上面的方法,所以即使我没有单击第一个单元格,我也会设置变量。
我不确定这是否清楚。我该怎么做?
2个回答

3
假设使用Windows Forms,比较朴素的方法是调用带有所需参数设置的函数:
假定使用Windows Forms,则较为朴素的方法是调用具有所需参数集的函数:
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);
    }

0

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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接