【问题】
需要在DataGridView中的单元格cell中添加按钮。
【解决过程】
1.参考:
去添加了如下代码:
Button gigUrlButton = new Button(); gigUrlButton.Text = "Buy Now"; gigUrlButton.Visible = true; gigUrlButton.AutoSize = false; dgvSearchResult.Controls.Add(gigUrlButton); Rectangle girUrlRect = dgvSearchResult.GetCellDisplayRectangle(12, dgvSearchResult.Rows.Count-2, true); //gigUrlButton.Width = dgvSearchResult.Columns[12].Width; //gigUrlButton.Height = dgvSearchResult.RowHeadersWidth; gigUrlButton.Width = girUrlRect.Width; gigUrlButton.Height = girUrlRect.Height; //gigUrlButton.Location = new Point(girUrlRect.X, girUrlRect.Y); gigUrlButton.Location = new Point(girUrlRect.Left, girUrlRect.Y);
对应的效果是:
2.很明显,其中第一行的按钮的长度有问题。
所以继续去调试修改。
3.后来参考了:
Win form DataGridView dynamically adding button column
得知有个
以及也找到了:
4.关于这些内容的总结,可以去看这里:
Column Types in the Windows Forms DataGridView Control
Class
Description
Used with text-based values. Generated automatically when binding to numbers and strings.
Used with Boolean and CheckState values. Generated automatically when binding to values of these types.
Used to display images. Generated automatically when binding to byte arrays, Image objects, or Icon objects.
Used to display buttons in cells. Not automatically generated when binding. Typically used as unbound columns.
Used to display drop-down lists in cells. Not automatically generated when binding. Typically data-bound manually.
Used to display links in cells. Not automatically generated when binding. Typically data-bound manually.
Your custom column type
You can create your own column class by inheriting the DataGridViewColumn class or any of its derived classes to provide custom appearance, behavior, or hosted controls. For more information, see How to: Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance
5.然后参考:
How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control
最终使用代码:
// Add a button column. DataGridViewButtonColumn gigUrlColumn = new DataGridViewButtonColumn(); gigUrlColumn.HeaderText = "Gig Url"; //gigUrlColumn.Name = "Gig Url name"; gigUrlColumn.Text = "Buy Now"; gigUrlColumn.UseColumnTextForButtonValue = true; gigUrlColumn.Width = 106; dgvSearchResult.Columns.Add(gigUrlColumn); DataGridViewButtonCell gigUrlCell = new DataGridViewButtonCell(); gigUrlCell.Value = singleGigInfo.gigUrl; dgvSearchResult.Rows.Add(......, gigUrlCell);
实现了按钮列的效果:
【总结】
更多的内容,比如添加button的事件,待有空再添加。