简体   繁体   中英

Programmatically Click Row Header in DataGridView C#

I am searching everywhere for code to programmatically Click a specific DataGridView row header, after processing a certain code sequence.

Everything I have found allows to select or highlight a row, column or cell; but nothing to date Clicks the Row Header ie. fires the

private void dgvMyGrid_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {}

Method.

Any help on this would be greatly appreciated.

The solution depends on what exactly you want to achieve.

To simply make the code in the dgvMyGrid_RowHeaderMouseClick run in the simplest way, as Tzah Mama wrote, it is enough to write:

dgvMyGrid_RowHeaderMouseClick(null, null);   

Note 1: It is important to add a coment to the event code to document that it can be called in this special and not normal way. Especially since this doesn't provide the parameters the code might expect.

Note 2: If your code needs some of the parameters you can try to provide them:

  • It is trivial to provide the sender simply as dgvMyGrid
  • If you are not coding a DataGridView instance but an inherited class you replace the dvg name simply with this

  • The second parameter is complex and not all its parts can be easily provided, but probably are not needed either.

Here is the basic code to create it:

int row = ??    // your target row
int col= -1;    // no column
int x = 0;      // no offsets..
int y = 0;      // ..
int delta = 0; // no mouse wheel

DataGridViewCellMouseEventArgs E = new DataGridViewCellMouseEventArgs(col, row, x, y,
                          new MouseEventArgs(MouseButtons.Left, clicks, x, y, delta));

Note 3: Sometimes it is important to know whether an event has been called by a real user action or by code. Leaving a paremter null is a simple way to signal this. Again: Key is documentation !

But maybe you need the effect of the rowHeader click? Which may be a row select, depending on the SelectionMode. This will not work by calling the script! Instead you must code the select as well:

 DGV1.Rows[row ].Selected = true;

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