繁体   English   中英

如何以编程方式单击DataGridView的单元格?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM