Programmatically perform click on a DataGridView Button Cell from another Button

前端 未结 2 1698
长情又很酷
长情又很酷 2021-01-21 17:16

I have a question regarding DataGridView control in .NET.

I inserted a DataGridView from the toolbox and I connected it with a database that I

2条回答
  •  长情又很酷
    2021-01-21 17:55

    If you want to generate programmatically click on DataGridViewButtonCell instance, you can use DataGridViewCell.AccessibilityObject property and call DoDefaultAction method.

    Something like this (sorry for C#, I'm sure you can translate it to VB):

    DataGridViewButtonCell otherCell = ...;
    otherCell.AccessibilityObject.DoDefaultAction();
    

    Test:

    using System;
    using System.Linq;
    using System.Windows.Forms;
    
    namespace Samples
    {
        static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                var form = new Form();
                var grid = new DataGridView { Dock = DockStyle.Fill, Parent = form, AutoGenerateColumns = false };
                var col0 = new DataGridViewTextBoxColumn { Name = "Col0", HeaderText = "Col0", DataPropertyName = "Col0" };
                var col1 = new DataGridViewButtonColumn { Name = "Col1", HeaderText = "Col1", DataPropertyName = "Col1" };
                grid.Columns.AddRange(new DataGridViewColumn[] { col0, col1 });
                grid.CellContentClick += (sender, e) =>
                {
                    MessageBox.Show("Clicked Cell[" + e.RowIndex + "," + e.ColumnIndex + "]");
                };
                grid.DataSource = Enumerable.Range(0, 10).Select(n => new { Col0 = "Cell[" + n + ",0]", Col1 = "Cell[" + n + ",1]" }).ToList();
                var button = new Button { Dock = DockStyle.Bottom, Parent = form, Text = "Click" };
                button.Click += (sender, e) =>
                {
                    var cell = grid.CurrentRow.Cells[col1.Index];
                    cell.AccessibilityObject.DoDefaultAction();
                };
                Application.Run(form);
            }
        }
    }
    

提交回复
热议问题