C#怎么自动触发事件?

form1的代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace net5WinFormsApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Debug.WriteLine("测试自动触发这个事件");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Grid.dv = dataGridView1;
            Grid.TestAutoClickCell();
        }
    }
}

Grid.cs的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace net5WinFormsApp
{
    public static class Grid
    {
        public static Form1 form1 { get; set; }
        public static DataGridView dv { get; set; }

        /// <summary>
        /// 测试自动触发点击单元格事件
        /// </summary>
        public static void TestAutoClickCell()
        {
            //在这里面如何触发dataGridView1_CellClick这个事件啊?
            dv.CellClick += Dv_CellClick;
        }

        private static void Dv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            throw new NotImplementedException();
        }
    }
}

我想通过Grid.cs里的TestAutoClickCell()方法自动触发Form1里的dataGridView1_CellClick事件,应该怎么做才能实现啊?求大神指点一下,非常感谢!

阅读 3.2k
1 个回答
新手上路,请多包涵

我猜你是希望点击DataGridView外部按钮button3时,其行为就像是点击某个(选中的?)单元格?
那应该不需要静态 Grid 类,而是把 dataGridView1_CellClick 内的逻辑抽取成另外一个方法,比如:

 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    OnDataGridViewCellClick(sender as DataGridView, e.RowIndex, e.ColumnIndex);
}

void OnDataGridViewCellClick(DataGridView dgv, int row, int column,...)
{
    Debug.WriteLine("测试自动触发这个事件");
}

然后在 button3_Click 里面

//TODO: 取得 dataGridView1 的选中行和列的索引,比如命名为  selectedRowIndex, selectedColIndex

OnDataGridViewCellClick(dataGridView1, selectedRowIndex, selectedColIndex);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进