MarcNacionales
MarcNacionales

Reputation: 11

set backcolor using DataGridViewButtonColumn C# winform

Hello. I'm trying to set backcolor of the button on datagridview using c# WinForm but i don't know how. Please Help me to solve this problem. Thank You

Here is my code:

        var model = FDBContext.oFDBEntity.tMasters.Where(t => t.trGroup_c == "POSMOD").ToList();

        dgModuleView.DataSource = model;
        dgModuleView.SelectionMode = DataGridViewSelectionMode.CellSelect;
        dgModuleView.Columns[0].HeaderText = "Code";
        dgModuleView.Columns[0].Width = 0;
        dgModuleView.Columns[1].HeaderText = "Description";
        dgModuleView.Columns[1].Width = 400;

        dgModuleView.Columns[2].Visible = false;
        dgModuleView.Columns[3].Visible = false;
        dgModuleView.Columns[4].Visible = false;
        dgModuleView.Columns[5].Visible = false;
        dgModuleView.Columns[6].Visible = false;
        dgModuleView.Columns[7].Visible = false;
        dgModuleView.Columns[8].Visible = false;
        dgModuleView.Columns[9].Visible = false;


        var button = new DataGridViewButtonColumn
        {
            FlatStyle = FlatStyle.Flat,
            Width = 50

        };
        var button1 = new DataGridViewButtonColumn
        {
            FlatStyle = FlatStyle.Flat,
            Width = 50
        };



        dgModuleView.Columns.Add(button);
        dgModuleView.Columns.Add(button1);

Upvotes: 0

Views: 1763

Answers (3)

Michael Smith
Michael Smith

Reputation: 75

call this from formLoad()

yourGrid.DefaultCellSyle.BackColor = Color.Green;

this will change all cells to the color you want.

yourGrid.DefaultCellStyle.SelectionBackColor = Color.Yellow;

this will mean when row is selected the color is yellow.

Upvotes: 0

trashr0x
trashr0x

Reputation: 6565

//declare a DataGridViewCellStyle
DataGridViewCellStyle style = new DataGridViewCellStyle();
//backcolor when the button is not selected
style.BackColor = Color.Green;
//backcolor when the button is selected
style.SelectionBackColor = Color.Yellow;

var button = new DataGridViewButtonColumn
    {
        FlatStyle = FlatStyle.Popup,
        //assign the style property to DefaultCellStyle of DataGridViewButtonColumn
        DefaultCellStyle = style,
        Width = 50
    };

//finally, add the button column to your DataGridView control
dgModuleView.Columns.Add(button);

All the properties exposed by DataGridViewButtonColumn (including DefaultCellStyle) can be found here.

Information about cell styles in the DataGridView control can be found here.

Upvotes: 2

MarcNacionales
MarcNacionales

Reputation: 11

It Doesn't work. There is no BackColor on DefaultCellStyle

This is the correct.

var button = new DataGridViewButtonColumn
    {
        FlatStyle = FlatStyle.Popup,
        DefaultCellStyle = ?
        Width = 50
    };

Upvotes: -1

Related Questions