Search code examples
c#winformsgridviewdatagridviewcolumnscada

How to Add Labels(not just one) in DataGridView cell


I need a grid which has some different color labels in the last column as below. I know how to do with one label but i need 4 and need to make them visible or invisible with the value(değer) on the grid.

for example

  if value is below 20 the red label will appear,

  if value is over 40 the yellow and orange will appear same time,

  if value is between 20-40 green label will appear... 

any help will be appreciated.

grid


Solution

  • You need a function which looks like this:

    void UpdateGridColumnLabels(int index){
        int width = column.Width;
        int height = gridRow.Height;
        Bitmap bmp = new Bitmap(width, height, g);
        Graphics g = Graphics.FromImage(bmp);
        if(value < 20)
            g.FillRect(Brushes.Red, 0, 0, width / 3, height);
        else if(value >= 20 && value < 40)
            g.FillRect(Brushes.Orange, width/3, 0, width / 3, height);
        else
            g.FillRect(Brushes.Yellow, 2 * width/3, 0, width / 3, height);
        gridViewImageColumn[index] = bmp;
    }
    

    Here you are creating a bitmap that fits into your cell. Then you are using Graphics class to add labels dynamically depending on your conditions. Afterwards this bitmap with labels becomes the content of the cell.