Can't change datagridview cell color when using a datasource

前端 未结 2 1234
南旧
南旧 2021-01-05 02:35

I\'ve got an interesting issue. I am trying to use a datatable as a data source for a datagridview. I want to color some of the cells of the table to indicate various things

2条回答
  •  时光取名叫无心
    2021-01-05 03:20

    If you try and set the cell colour within the constructor of the form you will be hitting before the data binding is completed so the changes to the cells don't stick (don't ask me why, just one of those gotchas with the DataGridView.

    The most straightforward fix to this is to set the colours a little later - usually within a DataBindingComplete event handler:

    void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow;
    }
    

    This is appropriate for static colouring of the grid - if you want the colours to change according to the changes within the grid then use the CellFormatting event to change the cells.

提交回复
热议问题