以下是我能想到的几个选项:
- 到目前为止,最简单的方法是为每个
Button 添加一个Column。 (推荐!)
- 你可以创建一个自定义单元格类型,也许是一个
Panel 子类和你想要的Buttons。这涉及实现IDataGridViewEditingControl iterface 至少有十几个字段和方法,以及两个从DataGridViewColumn 和DataGridViewCell 派生的自定义类,还有更多事情要做。简而言之,大量工作!对于一个复杂的编辑控件来说可能是值得的。对于一些Buttons 肯定不是! (不推荐!)
- 或者您可以在
CellPainting 事件中通过一点所有者绘图魔法伪造Buttons。见下文..!
- 或者您可以在作用于当前行的
DataGridView外部添加一个复杂的控件。 通常的方式!
这是一个有趣的小例子,所有者在DatagGridView DGV 的第四个Column 中绘制了四个“SIDU”命令:
private void Form1_Load(object sender, EventArgs e)
{
DGV.Rows.Add(12);
for( int i = 0; i< DGV.Rows.Count; i++)
{
DGV[0, i].Value = i;
DGV[1, i].Value = R.Next(1000);
DGV[2, i].Value = rights[R.Next(rights.Count)];
DGV[3, i].ReadOnly = true;
}
}
List<string> rights = new List<string>
{ "SIDU", "SID-", "SI-U", "S-DU", "SI--", "S--U", "S-D-", "S---" };
Dictionary<char, string> rightsTexts = new Dictionary<char, string>
{ { 'S', "Select" }, { 'I', "Insert" }, { 'D', "Delete" }, { 'U', "Update" } };
Random R = new Random(1);
private void DGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == 3 && e.RowIndex >= 0)
{
string r = DGV[2,e.RowIndex].Value.ToString();
StringFormat format = new StringFormat()
{ LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center};
int w = e.CellBounds.Width / 4;
int y = e.CellBounds.Y + 1;
int h = e.CellBounds.Height - 2;
e.PaintBackground(e.CellBounds, false);
for (int i = 0; i < 4; i++)
{
int x = e.CellBounds.X + i * w;
Rectangle rect = new Rectangle(x, y, w, h);
ControlPaint.DrawButton(e.Graphics, rect, ButtonState.Normal);
if (rightsTexts.ContainsKey(r[i]))
e.Graphics.DrawString(rightsTexts[r[i]], DGV.Font,
SystemBrushes.WindowText, rect ,format );
}
e.Handled = true;
}
}
private void DGV_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex == 3 && e.RowIndex >= 0)
{
DataGridViewCell cell = DGV[e.ColumnIndex, e.RowIndex];
int w = cell.Size.Width;
int buttonIndex = e.X * 4 / w;
Text = rightsTexts.ElementAt(buttonIndex).Value;
}
}
绘图的东西被扔掉了,所以你可以花更多的精力来微调它。..
我已选择在可见单元格中显示权限以进行演示。对于生产来说,action cell 的价值是显而易见的。