Skip to main content
 首页 » 编程设计

c#之如何将按钮添加到任何 datagridview 列的最后一个单元格

2024年02月06日14lexus

我想在任何列的最后一个单元格中添加按钮。这是行不通的。我该怎么做?

foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
    DataGridViewButtonCell button = (row.Cells["1"] as DataGridViewButtonCell); 
} 

编辑:我不想添加列。我想将这些按钮添加到任何列的最后一个单元格,而不是行的。

请您参考如下方法:

您必须为每个要装饰的列创建一个 DataGridViewButtonCell:

DataGridViewButtonCell cell_1 = new DataGridViewButtonCell(); 

然后您可以用 DataGridViewButtonCells 替换原来的 Cells:

dataGridView1[oneOfYourButtonColumnIndices , buttonRowIndex] = cell_1; 

请注意,您需要为每个 Button 创建单独的 Cells!每个只能添加一次!

您可以根据需要设置 Cell 的样式:

cell_1.Value = "Conquer"; 
cell_1.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; 

无论您如何不能向它注册任何事件,因为 DataGridViewCell 类型不是 Control 并且不实现事件模型。

相反,所有事件都必须在 DataGridView 中处理。这是一个例子:

List<int> YourButtonColumnIndices = new List<int> {3,5,7}; 
 
private void DGV_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    DataGridViewCell cell = DGV[e.ColumnIndex, e.RowIndex]; 
 
    // check if we have hit a button cell.. 
    if (YourButtonColumnIndices.Contains(e.ColumnIndex) && cell is DataGridViewButtonCell ) 
    { 
        Console.WriteLine(cell.Value.ToString()); 
        // do things that depend on the button: 
        // if (cell.Value == "Conquer")  doConquer(..); 
        // else (cell.Value == "Command")  doCommand(..); 
        // .. 
    } 
} 

您可以看到我可以像往常一样访问单元格的值。它也显示为按钮的文本。

请注意,所有 Cell 都有一个 Tag 属性,您可以在其中存储您喜欢的任何内容,包括委托(delegate)!

另请注意,在您的模型中,当您插入或删除行时,按钮的行可能会发生变化。因此,您应该注意仅在添加按钮时引用 buttonRowIndex 或使其保持最新。我没有在 Click 事件中检查它,因为列索引加上单元格类型就足够了。如果不是,您还可以检查值..

当然,您可以根据需要编写 doCommand 方法的代码,根据需要添加参数。

顺便说一句:常规按钮始终是 Silver 或您的系统在其配色方案中为按钮设置的任何颜色。但是您可以制作它们 FlatStyle 按钮,瞧,将使用 Cell 的背景色(和/或 Forecolor):

 cell_1.FlatStyle = FlatStyle.Flat; 
 cell_1.Style.BackColor = Color.LightSkyBlue; 

如果您有超过两个或三个这样的按钮,您可能需要创建一个Dictionary 来管理它们,可能像这样:

Dictionary<int, string> buttonList = new Dictionary<int, string>(); 
buttonList.Add(3, "Save Operator"); 
buttonList.Add(5, "Save An.1"); 
buttonList.Add(7, "Save An.2"); 

并用它来创建它们:

foreach(int i in buttonList.Keys) 
  { 
     DataGridViewButtonCell cell= new DataGridViewButtonCell(); 
     cell.Value = buttonList[i]; 
     cell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; 
     dataGridView1[i, buttonRowIndex] = cell; 
  } 

并在 CellClick 中检查它们:

if (buttonList.Keys.Contains(e.ColumnIndex) && cell is DataGridViewButtonCell ) 
{   
  if (e.ColumnIndex] == 3) doStuff3() 
  else if (e.ColumnIndex] == 5) doStuff5() 
  //..