我已經創建自定義列(DataGridViewButtonControlColumn)和單元格(ButtonControlCell)類來保存System.Windows.Forms.Button控件。按鈕被添加到列中並正確顯示。 在將按鈕設置爲ButtonControlCell的值之前,我附加了「Click」的事件處理程序。但是這個處理程序在單擊按鈕時不會被調用。按鈕點擊事件沒有從自定義DataGridViewCell觸發
我將按鈕添加到DataGridView控件的覆蓋Paint函數中。
是否有任何具體的步驟,我必須按照DataGridView註冊按鈕?
代碼:
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,但它並沒有按照我想要的方式行事。控件被調整大小以填充單元格,並且找不到屬性來防止這種情況。 順便說一句,我暫時使用DataGridViewLinkColumn,直到我能弄清楚如何觸發點擊事件 – Gayan 2010-01-14 11:55:27