开发者

I want to programmatically generate a click on a DataGridView Row in C#

I have a DataGridView in a form and I want to programmatically click its first row. I have found code to select its rows or columns from code.

For eg.

datagridview.Columns[0].Selected = true;
datagridview.Rows[0].Sel开发者_Go百科ected = true;

However this code is not raising the click event on the datagridview. If any one has coded how to click a datagridview from code, please extend your kind help.


Simply call the event handler method e.g.:

datagridviewRowClickedEventHandler(new object(), new eventargs());

If you use the sender or e parameters in the event handler then you will need to work out how to pass in the correct values.


Insert the follwing code into your project where appropriate (Usually on the form which has the datagridview).
Make sure to change the name of the DataGridView from dataGridView1 to the appropriate one on your form.

private void Form1_Load(object sender, EventArgs e)
{
    //call the cell click event with the first cell as the parameters.
    dataGridView1_CellClick(dataGridView1, new DataGridViewCellEventArgs(0, 0));
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    //put your code for handling cell click here
}


It looks like you have the first half, setting the propers rows Selected value to true. Now you can programatically call the row click handler and it should proceed as if you had clicked it within the GUI.


datagridview.Columns[0].Selected = true;
datagridview.Rows[0].Selected = true;

It makes look the row like selected but it won't change dataGridView.CurrentRow. So it could be an issue.

dataGridView.CurrentCell = dataGridView[<column>, <row>];

will change CurrentRow value too.

Hope it will help.


I assume you want to apply DataSource and select the first row? Right?

The best way to do it like this

private async void DgvAreas_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{

}

And here is the code to simulate click on row.

DgvAreas_RowStateChanged(dgvAreas, new DataGridViewRowStateChangedEventArgs(dgvAreas.Rows[0],  DataGridViewElementStates.Selected));

In my case I have 3 DataGridViews so I populate the first one easly. The second one I populate when user click the first DataGridView and in this case I use DgvStaff_RowStateChanged event.

And in this event DgvStaff_RowStateChanged I have the code to get data async and populate the third DataGridView and after I apply data source for the second DataGridView I need to get data for the first row of this view and display it in the third DataGridView. It is cascade logic.

private async void DgvStaff_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            try
            {
                // For any other operation except, StateChanged, do nothing
                if (e.StateChanged != DataGridViewElementStates.Selected) return;

                if (sender is MetroFramework.Controls.MetroGrid)
                {
                    if ((sender as MetroFramework.Controls.MetroGrid).SelectedRows.Count > 0)
                    {
                        dgvGeoData.DataSource = null;
                        dgvAreas.DataSource = null;

                        metroProgressSpinnerMain.Visible = true;
                        panelFilter.Enabled = false;

                        dgvAreas.RowStateChanged -= DgvAreas_RowStateChanged;

                        var selectedRow = (sender as MetroFramework.Controls.MetroGrid).SelectedRows[0];
                        var machineModelShortView = (MachineModelShortView)selectedRow.DataBoundItem;

                        var startTime = Convert.ToDateTime(dateTimePickerStart.Value.ToShortDateString());
                        var endTime = Convert.ToDateTime(metroDateTimeEnd.Value.ToShortDateString());
                        var areas = await UpdateAreaItems(machineModelShortView.MachineID, startTime, endTime);

                        if (areas.Any())
                        {
                            BeginInvoke((Action)(() =>
                            {
                                dgvAreas.DataSource = areas.OrderBy(x => x.AreaID).ThenBy(x => x.TimeStart).ToList();
                                dgvAreas.RowStateChanged += DgvAreas_RowStateChanged;

                                // !!! This is how you simulate click to the FIRST ROW dgvAreas.Rows[0]
                                DgvAreas_RowStateChanged(dgvAreas, 
                                    new DataGridViewRowStateChangedEventArgs(dgvAreas.Rows[0],  DataGridViewElementStates.Selected));

                                metroProgressSpinnerMain.Visible = false;
                                panelFilter.Enabled = true;
                            }));
                        }
                        else
                        {
                            BeginInvoke((Action)(() =>
                            {
                                metroProgressSpinnerMain.Visible = false;
                                panelFilter.Enabled = true;
                            }));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }

And here

   private async void DgvAreas_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            try
            {
                // For any other operation except, StateChanged, do nothing
                if (e.StateChanged != DataGridViewElementStates.Selected) return;

                //Get GeoData
                if (sender is MetroFramework.Controls.MetroGrid)
                {
                    if ((sender as MetroFramework.Controls.MetroGrid).SelectedRows.Count > 0)
                    {
                        dgvGeoData.DataSource = null;
                        metroProgressSpinnerMain.Visible = true;
                        panelFilter.Enabled = false;

                        var selectedRow = (sender as MetroFramework.Controls.MetroGrid).SelectedRows[0];
                        var areaItem = (AreaItem)selectedRow.DataBoundItem;
                        var geoData = await UpdateWDataPositionItems(areaItem.MachineID, areaItem.TimeStart, areaItem.TimeEnd.Value);

                        if (geoData.Any())
                        {
                            BeginInvoke((Action)(() =>
                            {
                                dgvGeoData.DataSource = geoData.OrderBy(x => x.AtTime).ToList();
                                metroProgressSpinnerMain.Visible = false;
                                panelFilter.Enabled = true;
                            }));
                        }
                        else
                        {
                            BeginInvoke((Action)(() =>
                            {
                                metroProgressSpinnerMain.Visible = false;
                                panelFilter.Enabled = true;
                            }));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜