HOW TO SET DATAGRIDVIEW CELL STYLE UNCHANGEABLE

Samuel Fernandes

Total Post:159

Points:1117
Posted by  Samuel Fernandes
C# 
C#
 1280  View(s)
Ratings:
Rate this:

I'm trying to set different back color of my DayaGridview rows by specific column

This is my Code:

private void SetFormat_dgv_Scheduled(string columnsname)

    {

        dgv_Scheduled.Sort(dgv_Scheduled.Columns[columnsname], ListSortDirection.Ascending);

        Color clr = Color.Red;

        string dt = (Convert.ToDateTime(dgv_Scheduled.Rows[0].Cells[columnsname].Value)).ToShortDateString();

        foreach(DataGridViewRow row in dgv_Scheduled.Rows)

        {

            if (Convert.ToDateTime(row.Cells[columnsname].Value).ToShortDateString() != dt)

            {

                if(clr==Color.Red)

                {

                    clr = Color.LightBlue;

                }

                else

                {

                    clr = Color.Red;

                }

            }     

             row.DefaultCellStyle.BackColor = clr;

        }          

    }

It works fine.

But when I click header to autosort, all format will set to default style.

(All red rows change back to white)

Is there any way that I can set format unchangeable?

Thanks.

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: How to set DataGridView cell style unchangeable

    Hi Samuel,


    Try calling  SetFormat_dgv_Scheduled method in CellFormatting Event as shown

       private void SetFormat_dgv_Scheduled(string columnsname)

        {

            //dataGridView1.Sort(dataGridView1.Columns[columnsname], ListSortDirection.Ascending);

            Color clr = Color.Red;

            string dt = (Convert.ToDateTime(dgv_Scheduled.Rows[0].Cells[columnsname].Value)).ToShortDateString();

            foreach (DataGridViewRow row in dgv_Scheduled.Rows)

            {

                if (Convert.ToDateTime(row.Cells[columnsname].Value).ToShortDateString() != dt)

                {

                    if (clr == Color.Red)

                    {

                        clr = Color.LightBlue;

                    }

                    else

                    {

                        clr = Color.Red;

                    }

                }

                row.DefaultCellStyle.BackColor = clr;

            }

        }

        private void dgv_Scheduled_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)

        {

            SetFormat_dgv_Scheduled("columnsname");

        }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!