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
Win form DataGridView dynamically adding button column
提问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 DataGridViewButtonCell
and then checking out the properties on that?
不久前我尝试了完全相同的事情,但无法使其正常工作;我的解决方案(因为它只是一个测试应用程序)是更改按钮单元的背景颜色并进行测试。好可怕。但是,回顾代码 - 您是否尝试row.Cells["ButtonColumnName"]
将 a转换为 aDataGridViewButtonCell
然后检查其属性?
回答by spatulon
You might find this MSDN article useful: How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control
您可能会发现这篇 MSDN 文章很有用:如何:禁用 Windows 窗体 DataGridView 控件中按钮列中的按钮
回答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;