C#中DataGridView中的按钮列?

时间:2012-07-16 00:09:04

标签: c# winforms datagridview

我正在尝试将所有按钮的文本设置为“设置文本”。我做了这个,但它没有用......我怎么办?

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

另外,我如何为这些按钮设置onclick事件?

3 个答案:

答案 0 :(得分:2)

试试这个:

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

结果:

enter image description here

和On点击事件:

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

答案 1 :(得分:2)

更改按钮文字。

const int BUTTON_COLUMN_INDEX = 0;

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

即使在DataGridView中也无法单击按钮。 相反,您必须处理CellClick事件并检查是否单击了您想要的列。

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

答案 2 :(得分:0)

试试这个

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