views:

4696

answers:

3

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.

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!
}
+2  A: 

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?

Graham Clark
A: 

You might find this MSDN article useful: How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control

spatulon
A: 

Use

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