1

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?

1
  • We need to see more. ASPX code for the grid and code behind. Commented Jul 16, 2012 at 0:11

3 Answers 3

2

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
            }
        }
Sign up to request clarification or add additional context in comments.

1 Comment

You missed the onclick event part.
2

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

1 Comment

+1 for adding the && e.RowIndex >= 0 ... it turns out, i needed that.
0

Try This

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

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.