繁体   English   中英

按钮单击事件未从自定义DataGridViewCell触发

[英]Button click event not firing from custom DataGridViewCell

我创建了自定义列(DataGridViewButtonControlColumn)和单元格(ButtonControlCell)类来保存System.Windows.Forms.Button控件。 这些按钮将添加到列中并正确显示。 在将按钮设置为ButtonControlCell的值之前,我为“ Click”附加了事件处理程序。 但是,单击按钮时不会调用此处理程序。

我将按钮添加到重写的Paint函数中的DataGridView控件中。

要在DataGridView中注册Button,我需要遵循什么特定的步骤吗?

码:

public class ButtonControlCell : DataGridViewTextBoxCell
    {
.
.
.
protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);

            if (btnVal != null)
            {
                btnVal.Size = new System.Drawing.Size(80, 20);
                btnVal.Location = cellBounds.Location;
                this.DataGridView.Controls.Add(btnVal);
            }            
        }
.
.
.
protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
        {
            // This is not called when the button is clicked (which is correct I guess)
            base.OnMouseClick(e);

            if (btnVal != null)
            {
                btnVal.PerformClick();
            }
        }
.
.
}

在执行中:

private void AddButtonCell(string sText, EventHandler oEh, DataGridViewButtonColumn oClm, DataGridView dgvParent, int iRow, int iColumn)
        {
            Button btnTemp = new Button();
            btnTemp.Height = 20;
            btnTemp.Width = 60;
            btnTemp.Anchor = AnchorStyles.Top;
            btnTemp.Text = sText;
            btnTemp.Click += new EventHandler(btnTemp_Click);
            btnTemp.Tag = new Point(iRow, iColumn);

            Controls.Add(btnTemp);

            dgvParent.Rows[iRow].Cells[iColumn].Value = btnTemp;
        }

        void btnTemp_Click(object sender, EventArgs e)
        {
            Button btnSender = (Button)sender;

            DataGridViewRow r = dgvResults.Rows[((Point)btnSender.Tag).X];

            TagInfo oRet = new TagInfo((string)r.Cells[iTitleColIndex].Value, (string)r.Cells[iArtistColIndex].Value,
                (string)r.Cells[iAlbumColIndex].Value);
            oRet.imgAlbumArt = (System.Drawing.Image)r.Cells[iArtColIndex].Tag;
            oParent.TagWithInfo(oRet, true);
        }

如果您的目标是只有一个按钮,则用户可以单击,则可以使用内置的DataGridViewButtonColumn( DataGridViewButtonColumn )。

实现此目的的方法是捕获在DataGrid上执行的事件(例如,单击按钮),获取控件并根据此执行其他任务。 通过阅读有关自定义DataGridView的一些教程,找到了答案。

暂无
暂无

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

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