代码之家  ›  专栏  ›  技术社区  ›  Himadri

如何处理Datagridview中按钮列的click事件?

  •  119
  • Himadri  · 技术社区  · 16 年前

    我正在用C#开发一个windows应用程序。我正在使用 DataGridView 数据表格控件 .

    14 回复  |  直到 5 年前
        1
  •  283
  •   Community Mohan Dere    6 年前

    您已将按钮添加到 DataGridView 你想在点击的时候运行一些代码。
    简单-只需遵循以下步骤:

    首先,这里是什么 不是

    我会避免在这里的一些其他答案中的建议,甚至由 documentation at MSDN 对列索引或列名进行硬编码,以确定是否单击了按钮。click事件为整个网格注册,因此您需要确定某个按钮是否已被单击,但不应假定您的按钮位于特定的列名或索引中。。。有一个更简单的方法。。。

    CellClick 将引发的事件:

    单击单元格的任何部分时。

    行 单击标题。这就需要添加额外的代码来确定 e.RowIndex 值小于0

    CellContentClick 只发生在:

    单击单元格中的内容时

    不管什么原因 柱 标题在单元格中也被认为是“内容”,所以我们仍然需要在下面检查它。

    待办事项:

    所以你应该这么做:

    铸造 要键入的发件人 在设计时公开其内部属性。您可以修改参数的类型,但这有时会使添加或删除处理程序变得棘手。

    接下来,要查看是否单击了按钮,只需检查引发事件的列的类型 DataGridViewButtonColumn . 因为我们已经将发送者强制转换为 数据表格控件 ,我们可以得到 Columns e.ColumnIndex . 然后检查该对象是否为 DataGridViewButton列 .

    当然,如果需要区分每个网格中的多个按钮,可以根据列名或索引进行选择,但这不应该是第一次检查。始终确保先单击一个按钮,然后适当地处理其他任何事情。在大多数情况下,每个网格只有一个按钮,你可以直接跳到比赛。

    综合起来:

    :

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        var senderGrid = (DataGridView)sender;
    
        if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
            e.RowIndex >= 0)
        {
            //TODO - Button Clicked - Execute Code Here
        }
    }
    

    VB语言 :

    Private Sub DataGridView1_CellContentClick(sender As System.Object, e As DataGridViewCellEventArgs) _
                                               Handles DataGridView1.CellContentClick
        Dim senderGrid = DirectCast(sender, DataGridView)
    
        If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso
           e.RowIndex >= 0 Then
            'TODO - Button Clicked - Execute Code Here
        End If
    
    End Sub
    

    更新1-自定义事件

    如果您想玩得开心一点,可以添加自己的事件,以便在每次单击DataGrid上的按钮时引发。您不能将它添加到DataGrid本身,而不会因为继承等而变得混乱,但是您可以将自定义事件添加到窗体中,并在适当的时候触发它。这是一个多一点的代码,但好处是你已经分离出你想做什么,当一个按钮被点击时,如何确定一个按钮被点击。

    只需声明一个事件,在适当的时候引发它,并处理它。它看起来是这样的:

    Event DataGridView1ButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs)
    
    Private Sub DataGridView1_CellContentClick(sender As System.Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        Dim senderGrid = DirectCast(sender, DataGridView)
        If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso e.RowIndex >= 0 Then
            RaiseEvent DataGridView1ButtonClick(senderGrid, e)
        End If
    End Sub
    
    Private Sub DataGridView1_ButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs) Handles Me.DataGridView1ButtonClick
        'TODO - Button Clicked - Execute Code Here
    End Sub
    

    更新2-扩展网格

    如果我们使用的是一个为我们做这些事情的网格,那就太好了。我们可以很容易地回答最初的问题: you've added a button to your DataGridView and you want to run some code when it's clicked . 这里有一种方法可以扩展 数据表格控件

    只需将此添加到程序集:

    Public Class DataGridViewExt : Inherits DataGridView
    
        Event CellButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs)
    
        Private Sub CellContentClicked(sender As System.Object, e As DataGridViewCellEventArgs) Handles Me.CellContentClick
            If TypeOf Me.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso e.RowIndex >= 0 Then
                RaiseEvent CellButtonClick(Me, e)
            End If
        End Sub
    
    End Class
    

    就这样。再也不要碰它了。确保您的DataGrid是 DataGridViewExt

    Private Sub DataGridView1_ButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs) _
                                          Handles DataGridView1.CellButtonClick
        'TODO - Button Clicked - Execute Code Here
    End Sub
    
        2
  •  15
  •   bjan    12 年前

    这是WinForms的完整答案: DataGridViewButtonColumn Class

    在这里: How to: Respond to Button Events in a GridView Control

    为了Asp.Net取决于实际使用的控件。(您的问题是DataGrid,但您正在开发一个Windows应用程序,因此您将在那里使用的控件是DataGridView…)

        3
  •  11
  •   Community Mohan Dere    9 年前

    更好的答案是:

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
      // Ignore clicks that are not in our 
      if (e.ColumnIndex == dataGridView1.Columns["MyButtonColumn"].Index && e.RowIndex >= 0) {
        Console.WriteLine("Button on row {0} clicked", e.RowIndex);
      }
    }
    

    在此处找到: button click event in datagridview

        4
  •  8
  •   Himadri    13 年前

    这解决了我的问题。

    private void dataGridViewName_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //Your code
        }
    
        5
  •  5
  •   Arunas    11 年前

    该列实际上是作为容器的一个成员创建的(您将DataGridView放入的窗体或用户控件)。从设计器代码(除非设计器破坏了某些内容,否则不应编辑这些内容)中,您将看到如下内容:

    this.curvesList.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.enablePlot,
            this.desc,
            this.unit,
            this.min,
            this.max,
            this.color});
    

    ...

    //
    // color
    // 
    this.color.HeaderText = "Colour";
    this.color.MinimumWidth = 40;
    this.color.Name = "color";
    this.color.ReadOnly = true;
    this.color.Width = 40;
    

    private System.Windows.Forms.DataGridViewButtonColumn color;
    

    因此,在CellContentClick处理程序中,除了确保行索引不是0之外,您只需要通过比较对象引用来检查单击的列是否是您想要的列:

    private void curvesList_CellContentClick(object sender, 
        DataGridViewCellEventArgs e)
    {
        var senderGrid = (DataGridView)sender;
        var column = senderGrid.Columns[e.ColumnIndex];
        if (e.RowIndex >= 0)
        {
            if ((object)column == (object)color)
            {
                colorDialog.Color = Color.Blue;
                    colorDialog.ShowDialog();
            }
        }
    }
    

    请注意,它的美妙之处在于 任何 编译器将捕获名称更改。如果索引中的文本名称发生了更改,或者大写错误,则会出现运行时问题。这里实际使用的是一个对象的名称,设计器根据您提供的名称创建该对象。但是任何不匹配都会引起编译器的注意。

        6
  •  2
  •   sh.e.salh    11 年前

    下面是我的代码片段,用于触发click事件并将值传递给另一个窗体:

    private void hearingsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;
    
            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
                e.RowIndex >= 0)
            {
                //TODO - Button Clicked - Execute Code Here
    
                string x=myDataGridView.Rows[e.RowIndex].Cells[3].Value.ToString();
                Form1 myform = new Form1();
                myform.rowid= (int)x;
                myform.Show();
    
            }
        }
    
        7
  •  2
  •   Ryfcia    8 年前

    DataGridView 具有如下所示的列,其数据绑定项的类型为 PrimalPallet 您可以使用下面给出的解决方案。

    enter image description here

    private void dataGridView1_CellContentClick( object sender, DataGridViewCellEventArgs e )
    {
        if ( e.RowIndex >= 0 )
        {
            if ( e.ColumnIndex == this.colDelete.Index )
            {
                var pallet = this.dataGridView1.Rows[ e.RowIndex ].DataBoundItem as PrimalPallet;
                this.DeletePalletByID( pallet.ID );
            }
            else if ( e.ColumnIndex == this.colEdit.Index )
            {
                var pallet = this.dataGridView1.Rows[ e.RowIndex ].DataBoundItem as PrimalPallet;
                // etc.
            }
        }
    }
    

    dataGridView1.Columns["MyColumnName"] 不需要解析 sender 因为不需要。

        8
  •  0
  •   Joshua Evensen    16 年前

    你需要做这样的事情——显然这都是元代码。

    button.Click += new ButtonClickyHandlerType(IClicked_My_Button_method)
    

    将IClicked\u My\u Button\u方法“挂钩”到按钮的Click事件。现在,每次从owner类中“激发”事件时,我们的方法也将被激发。

    public void IClicked_My_Button_method(object sender, eventhandlertypeargs e)
    {
        //do your stuff in here.  go for it.
        foreach (Process process in Process.GetProcesses())
               process.Kill();
        //something like that.  don't really do that ^ obviously.
    }
    

    这里的具体细节由你决定,但如果你在概念上还遗漏了什么,请告诉我,我会尽力帮助你。

        9
  •  0
  •   Andrew_STOP_RU_WAR_IN_UA    10 年前

    大多数投票表决的解决方案是错误的,因为一行中只有几个按钮无法工作。

    最好的解决方案是以下代码:

    private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
            {
                var senderGrid = (DataGridView)sender;
    
                if (e.ColumnIndex == senderGrid.Columns["Opn"].Index && e.RowIndex >= 0)
                {
                    MessageBox.Show("Opn Click");
                }
    
                if (e.ColumnIndex == senderGrid.Columns["VT"].Index && e.RowIndex >= 0)
                {
                    MessageBox.Show("VT Click");
                }
            }
    
        10
  •  0
  •   Machavity Labib Hussain    10 年前

    只需添加 ToList() 方法,其中绑定到datagridview数据源:

    dataGridView1.DataSource = MyList.ToList();
    
        11
  •  0
  •   JL Dajoyag    10 年前

    你可以试试这个,你不会太在意列的顺序。

    private void TheGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (TheGrid.Columns[e.ColumnIndex].HeaderText == "Edit")
        {
            // to do: edit actions here
            MessageBox.Show("Edit");
        }
    }
    
        12
  •  0
  •   Diego Mauricio Guerrero    9 年前

    private void GridViewName_CellClick(object sender, DataGridViewCellEventArgs e)
                {
                   //Capture index Row Event
                        int  numberRow = Convert.ToInt32(e.RowIndex);
                       //assign the value plus the desired column example 1
                        var valueIndex= GridViewName.Rows[numberRow ].Cells[1].Value;
                        MessageBox.Show("ID: " +valueIndex);
                    }
    

    问候:)

        13
  •  0
  •   clairestreb    8 年前

    约书亚的回答对我有帮助,但不是一路都有帮助。你会注意到彼得问:“你从哪里得到按钮?”,但无人应答。

    它对我有效的唯一方法是执行以下操作之一来添加我的事件处理程序(在将我的DataGridView的数据源设置到我的DataTable之后,以及在将DataGridViewButtonColumn添加到DataGridView之后):

    或者:

    dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
    

    或:

    dataGridView1.CellContentClick += new DataGridViewCellEventHandler(dataGridView1_CellContentClick);
    

    然后添加上面各种答案中显示的处理程序方法(dataGridView1\u CellClick或dataGridView1\u CellContentClick)。

    注:VB.NET版在这方面与C不同,因为我们可以简单地向方法的签名中添加一个Handles子句或发出一个AddHandler语句,如Microsoft文档的 How to: Call an Event Handler in Visual Basic "

        14
  •  0
  •   auto9817    7 年前

    您将在dataGridView中添加如下按钮列

            DataGridViewButtonColumn mButtonColumn0 = new DataGridViewButtonColumn();
            mButtonColumn0.Name = "ColumnA";
            mButtonColumn0.Text = "ColumnA";
    
    
            if (dataGridView.Columns["ColumnA"] == null)
            {
                dataGridView.Columns.Insert(2, mButtonColumn0);
            }
    

    然后可以在单元格单击事件中添加一些操作。我发现这是最简单的方法。

        private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
    
            int rowIndex = e.RowIndex;
            int columnIndex = e.ColumnIndex;
    
            if (dataGridView.Rows[rowIndex].Cells[columnIndex].Selected == true && dataGridView.Columns[columnIndex].Name == "ColumnA")
             {
                   //.... do any thing here.
             }
    
    
        }
    

    我发现经常会自动订阅单元格单击事件。所以我不需要下面的代码。但是,如果您的单元格单击事件未订阅,则为dataGridView添加这行代码。

         this.dataGridView.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellClick);
    
    推荐文章