1

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!
}

5 Answers 5

6

Use this:

foreach (DataGridViewRow row in dataGridView.Rows) 
{ 
    // DataGridViewButtonCell button = (row.Cells["ButtonColumnName"] as DataGridViewButtonCell); 
    row.Cells["ButtonColumnName"].Value = "ButtonText";
} 
Sign up to request clarification or add additional context in comments.

Comments

4

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?

Comments

1

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

buttonCol.UseColumnTextForButtonValue = true;

Comments

0

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

Comments

0

Use

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.