简体   繁体   中英

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. So no problem there.

But i want to automatically click on the first cell of the same DataGridView when I lauch my program. 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.

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

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). 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. You may set it in the Form_Load

if (DataGridView.Rows.Count >= 0)
{
    // Set the first cell
    DataGridView.CurrentCell = DataGridView.Rows(0).Cells(0);
    // Cell logic
    UserSelectedCell(DataGridView.CurrentCell);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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