Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a C# application that displays a data grid view. The data grid view
has a Debit column and a Credit column. I want to change the background colors of the Debit and Credit columns. Here is the code:

What I have tried:

dgvCheckRegister.Columns["Debit"].DefaultCellStyle.BackColor = Color.LightPink;
dgvCheckRegister.Columns["Credit"].DefaultCellStyle.BackColor = Color.LightGreen;


It works except every other column does not get change. What is wrong
with my code? Thank in advance.
Posted
Comments
PIEBALDconsult 10-Feb-24 20:57pm    
Every other column? Or every other row?

1 solution

If I try your code in my test app:
C#
DataTable dt = new DataTable();
string strConnect = SMDBSupport.SMInstanceStorage.GetInstanceConnectionString("VideoMaster");
using (SqlConnection con = new SqlConnection(strConnect))
    {
    try
        {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Videos", con);
        da.Fill(dt);
        MyDataGridView.DataSource = dt;
        }
    catch (Exception ex)
        {
        Debug.WriteLine(ex.ToString());
        }
    }
MyDataGridView.Columns[1].DefaultCellStyle.BackColor = Color.LightPink;
MyDataGridView.Columns[2].DefaultCellStyle.BackColor = Color.LightGreen;
I get what I expected: the second column has a pink background and the third has a green.

So you need to look at exactly what you see on your screen - which we can't look at - and also at the rest of your code to see what it is doing to your DGV.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900