繁体   English   中英

C# 动态DataGridViewCell点击事件

[英]C# Dynamic DataGridViewCell Click Event

我有一个 DGV 要单击,另一个要根据此单击类型创建并显示在屏幕上以用于特殊工作目的。 在其他 DGV 的某些单元格(某些行列逻辑)的创建过程中,将使用程序代码自动单击。 下面的代码执行此操作的 AUTO CLICK 代码部分。 但我相信必须有另一种方法(如在 Button PerformClick Event Fire 中)来实现此点击操作:

            DataGridViewCell dc;
            dc = MyDataGridView[0, 0];
            Rectangle rect = this.MyDataGridView.GetCellDisplayRectangle(0, 0, true);
            MouseButtons b = new MouseButtons();
            MouseEventArgs mev = new MouseEventArgs(b, 1, rect.X, rect.Y, 1);
            DataGridViewCellMouseEventArgs e = new DataGridViewCellMouseEventArgs(0, 0, rect.X + 2, rect.Y + 2, mev);
            MyDataGridView_CellMouseClick(dgvEntegCompany, e);

问题不是很清楚。 您只是在寻找CellClick事件吗?

编辑:那么您需要执行 CellClick 的内容吗? CellClick 是一个事件,所以它在单元格单击事件发生时触发。 它可以包含对方法的调用,如果您愿意,您也可以“动态地”独立调用该方法。

    // CellClick event
    private void dgItems_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        MyMessage(e.RowIndex, e.ColumnIndex);
    }

    // A user method
    private void MyMessage(Int32 irow, Int32 icol)
    {
        System.Windows.Forms.MessageBox.Show("A cell [" + irow  + ", " + icol  + "] was clicked!");
    }

    // invoking from a button
    private void button1_Click(object sender, EventArgs e)
    {
        MyMessage(this.dgItems.SelectedCells[0].RowIndex, this.dgItems.SelectedCells[0].ColumnIndex );
    }

编辑2:

没有自动点击之类的东西。

  • 如果您想在可能的事件中执行代码,请参见上面的代码
  • 如果要执行视觉更改,例如 select 一个单元格,只需执行此操作。 请注意,此操作取决于SelectionMode的设置,例如,它对于CellFullRowSelect的行为方式不同。 它会是这样的:
    this.DataGridView1.ClearSelection();
    this.DataGridView1.Rows[0].Cells[3].Selected = True;
  • 如果您正在寻找一种调用动作的方法(也称为计算机 AI 播放器),您很可能必须研究多线程,即BackgroundWorker并创建一个单独的线程来控制游戏/模拟/等。 那么问题仍然存在于光年之外

备注:你必须更好地表达你的问题,这意味着要花更多的精力来编写它。 你这样只是在浪费社区时间。

我会假设这就是你的意思……

“DataGridView 单元格的触发事件代码单击任意列 - 行”

... 是您想订阅当用户“点击”网格中的任何单元格时将触发的网格事件。

如果是这种情况……那么,订阅网格CellClickCellMouseClick事件。

如果您想订阅网格CellMouseClick事件,那么可以在设计器中完成该代码,或者您可以在InitializeComponent(); 方法被调用,它看起来像......

dataGridView1.CellMouseClick += new DataGridViewCellMouseEventHandler(dataGridView1_CellMouseClick);

然后您需要创建事件处理程序方法... dataGridView1_CellMouseClick. 在这种情况下,您可以检查DataGridViewCellMouseEventArgs object 以查看单击了哪个单元格。 object 具有用于单击单元格的行索引和列索引的属性。 下面是一个例子。

private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
  // This event will fire whenever a user clicks on a cell
  // we can get the row and column index of the "clicked" cell
  MessageBox.Show("Cell at Row: " + e.RowIndex + " Col: " + e.ColumnIndex + "  was clicked");
}

每次用户单击网格中的单元格时都会触发此事件。

目前尚不清楚您究竟想用当前代码完成什么。

甚至这两行代码也会执行所需的操作:

DataGridViewCellEventArgs e = new DataGridViewCellEventArgs(ColIdx, RowIdx);
MyDataGridvView_CellClick(myDGV, e); 

暂无
暂无

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

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