我认为您必须使用一些自定义CellPainting
并且不要将Text
of设置DataGridViewButtonColumn
为任何内容(默认情况下这是一个空字符串)。像这样:
private void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex > -1&&e.RowIndex > -1&&dataGridView.Columns[e.ColumnIndex] is DataGridViewButtonColumn)
{
if (e.Value == null) return;
e.Handled = true;
e.PaintBackground(e.CellBounds, true);
e.PaintContent(e.CellBounds);
//prepare format for drawing string yourself.
StringFormat sf = new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center };
e.Graphics.DrawString(((Button)e.Value).Text, dataGridView.Font, Brushes.Black, e.CellBounds, sf);
}
}
在您的情况下替换dataGridView
为d
, 看起来您使用代码创建了 DataGridView,如果是这样,您必须自己注册CellPainting
事件处理程序,如下所示:
d.CellPainting += dataGridView_CellPainting;
更新
要使您的 DataGridView 首先有一个 DataGridViewButtonColumn(无需在设计时添加),您必须在设置 DataGridView 的 DataSource 之前添加此代码:
DataGridViewButtonColumn col = new DataGridViewButtonColumn();
col.HeaderText = "Your header";
col.Name = "button";
col.DataPropertyName = "Your DataSource Data member";//This is very important to match the corresponding Property or DataMember name of your DataSource.
col.FlatStyle = FlatStyle.Popup;//I suggest this because it looks more elegant.
d.Columns.Add(col);
//----
d.DataSource = ...
我发现DisplayIndex
为您的 Button 列设置 不起作用,相反,您可能希望在DisplayIndex
之后设置它d.DataSource=...
,并且它可以工作:
d.DataSource = ... ;
d.Columns["button"].DisplayIndex = ...;