简体   繁体   English

我想以编程方式在 C# 中生成对 DataGridView 行的点击

[英]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.我在表单中有一个DataGridView ,我想以编程方式单击它的第一行。 I have found code to select its rows or columns from code.我找到了从代码中选择其行或列的代码。

For eg.例如。

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

However this code is not raising the click event on the datagridview.但是,此代码不会在 datagridview 上引发click event If any one has coded how to click a datagridview from code, please extend your kind help.如果有人编写了如何从代码中单击 datagridview 的代码,请扩展您的帮助。

Simply call the event handler method eg:只需调用事件处理程序方法,例如:

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.如果您在事件处理程序中使用 sender 或 e 参数,那么您将需要弄清楚如何传入正确的值。

Insert the follwing code into your project where appropriate (Usually on the form which has the datagridview).在适当的地方将以下代码插入到您的项目中(通常在具有 datagridview 的表单上)。
Make sure to change the name of the DataGridView from dataGridView1 to the appropriate one on your form.确保将 DataGridView 的名称从dataGridView1更改为表单上相应的名称。

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.看起来您有前半部分,将属性行Selected值设置为 true。 Now you can programatically call the row click handler and it should proceed as if you had clicked it within the GUI.现在您可以以编程方式调用行单击处理程序,它应该像您在 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 .它使行看起来像被选中,但它不会改变dataGridView.CurrentRow So it could be an issue.所以这可能是一个问题。

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

will change CurrentRow value too.也会改变CurrentRow值。

Hope it will help.希望它会有所帮助。

I assume you want to apply DataSource and select the first row?我假设您要应用DataSource并选择第一行? 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 DataGridView s so I populate the first one easly.就我而言,我有 3 个DataGridView所以我很容易填充第一个。 The second one I populate when user click the first DataGridView and in this case I use DgvStaff_RowStateChanged event.当用户单击第一个 DataGridView 时我填充的第二个,在这种情况下我使用DgvStaff_RowStateChanged事件。

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 .在这种情况下, DgvStaff_RowStateChanged我有代码来异步获取数据并填充第三个DataGridView ,在我为第二个DataGridView应用数据源后,我需要获取此视图第一行的数据并将其显示在第三个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);
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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