更改DataGridViewButtonCell值

时间:2016-03-27 13:29:42

标签: c# .net winforms button datagridview

我正在开发一个使用DataGridView控件的Windows窗体应用程序。这个DataGridView有一个包含按钮的单元格。默认按钮文本为Start,但当我尝试动态更改时,如:

((DataGridViewButtonCell)Myrow.Cells[9]).Value = "End";

或者只是喜欢

Myrow.Cells[9].Value = "End";

抛出以下异常:

An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll

我的完整代码是这样的:

void HighlightOnlineUsers()
{
     foreach (DataGridViewRow Myrow in dataGridView1.Rows)
     {
             if (Convert.ToInt32(Myrow.Cells[8].Value) > 0)
             {
                  Myrow.DefaultCellStyle.BackColor = Color.GreenYellow;
                  Myrow.Cells[9].Value = "End";
             }
             else {
                  Myrow.DefaultCellStyle.BackColor = Color.White;
                  ((DataGridViewButtonCell)Myrow.Cells["SessionAction"]).Value = "Start";
             }
     }
}

2 个答案:

答案 0 :(得分:3)

要为按钮添加不同的文本,您可以处理网格的CellFormatting事件,并将用于格式化列值的逻辑放在那里。

private void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    //If this is header row or new row, do nothing
    if (e.RowIndex < 0 || e.RowIndex == this.grid.NewRowIndex)
        return;

    //I suppose your button is at index 9
    if (e.ColumnIndex == 9)
    {
        //You can put your dynamic logic here
        //and use different values based on other cell values
        //for example based on cell at index 8      
        if (Convert.ToInt32(this.grid.Rows[e.RowIndex].Cells[8].Value) > 0)
            e.Value = "End";
        else
            e.Value = "Start";
    }
}

您应该将此处理程序分配给CellFormating事件:

this.grid.CellFormatting += grid_CellFormatting;

答案 1 :(得分:0)

for (int i = 0; i < dataGridView1.RowCount; i++)
{
  dataGridView1.Rows[i].Cells["Buttons"].Value = "some value";
}

注意"Buttons"是列的名称