Hunter Mitchell
Hunter Mitchell

Reputation: 7293

Button Column in DataGridView in C#?

i am trying to set the text of all the buttons to "Set Text". I have made this, but it did not work....How would i do this?

        foreach (DataGridViewButtonCell btn in dataGridView1.Rows)
        {
            btn.Text = "Set Text"; 
        }

Also, how would i have an onclick event for those buttons?

Upvotes: 1

Views: 17431

Answers (3)

uday kiran
uday kiran

Reputation: 1

Try This

        foreach (DataGridViewButtonCell btn in dataGridView1.Rows)
        {
            btn.Text = "Set Text";
            btn.UseColumnTextForButtonValue=true;
        }

Upvotes: 0

nunespascal
nunespascal

Reputation: 17724

Change the button text.

const int BUTTON_COLUMN_INDEX = 0;

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    row.Cells[BUTTON_COLUMN_INDEX].Value = "Set Text";
}

You cannot have a button click even in a DataGridView. Instead you must handle the CellClick event and check if the column you want was clicked.

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
    // Check if wanted column was clicked 
    if (e.ColumnIndex == BUTTON_COLUMN_INDEX && e.RowIndex >= 0) {
        //Perform on button click code
    }
}

Upvotes: 2

KF2
KF2

Reputation: 10143

try this:

 private void button1_Click(object sender, EventArgs e)
        {

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                DataGridViewCell cell = row.Cells[0];//Column Index
                cell.Value = "Set Text";
            }
        }

result:

enter image description here

and for On click event:

private void gw_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)//Column index
            {
                //Do Somethings
            }
        }

Upvotes: 2

Related Questions