C# Win 窗体 DataGridView 动态添加按钮列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/964135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:22:02  来源:igfitidea点击:

Win form DataGridView dynamically adding button column

c#winformsdatagridview

提问by Zoman

I'd like to add a button column dynamically to a DataGridView after it has been populated. The button column is visible after adding it, but when I try to loop through the DataGridView rows, I get a null for the button in each cell.

我想在填充后将按钮列动态添加到 DataGridView。添加按钮列后可见,但是当我尝试遍历 DataGridView 行时,每个单元格中的按钮都为空。

var buttonCol = new DataGridViewButtonColumn();
buttonCol.Name = "ButtonColumnName";
buttonCol.HeaderText = "Header";
buttonCol.Text = "Button Text";

dataGridView.Columns.Add(buttonCol);

foreach (DataGridViewRow row in dataGridView.Rows)
{
    var button = (Button)row.Cells["ButtonColumnName"].Value;
    // button is null here!
}

采纳答案by Graham Clark

I tried the exact same thing a while ago and couldn't get it working; my solution (as it was just a test application) was to change the background colour of the button cell and test for that. Pretty awful. However, looking back at the code - have you tried casting the row.Cells["ButtonColumnName"]to a DataGridViewButtonCelland then checking out the properties on that?

不久前我尝试了完全相同的事情,但无法使其正常工作;我的解决方案(因为它只是一个测试应用程序)是更改按钮单元的背景颜色并进行测试。好可怕。但是,回顾代码 - 您是否尝试row.Cells["ButtonColumnName"]将 a转换为 aDataGridViewButtonCell然后检查其属性?

回答by spatulon

回答by SO User

Use

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

回答by DeepakV

Use this:

用这个:

foreach (DataGridViewRow row in dataGridView.Rows) 
{ 
    // DataGridViewButtonCell button = (row.Cells["ButtonColumnName"] as DataGridViewButtonCell); 
    row.Cells["ButtonColumnName"].Value = "ButtonText";
} 

回答by Peyman Panjehbashi

You must add the bellow code in your code, then you can see "Button Text" on each boutton:

您必须在代码中添加以下代码,然后您可以在每个按钮上看到“按钮文本”:

buttonCol.UseColumnTextForButtonValue = true;