Change color of some rows in DataGridView

First column of my DataGridView is a number which represents Bill Number. I have given option to define print selection range. Two TextBoxes for "From Bill" and "To Bill". User will enter any number in these two Text Boxes. Suppose user enters: 220 To 225. So the color of the rows whose first column value lies in this range, must change. I attempted following code. It is working fine, but it is automatically using AlternatingRowStyle. And due to this, alternate rows are white. I want all rows of same color. How to do this?
private void ChangeRowColors()
        {
            
            try
            {
                int RangeFrom = Convert.ToInt32(txtFromPage.Text);
                int RangeTo = Convert.ToInt32(txtToPage.Text);
 
                for (int i = 0; i <= dgvBills.Rows.Count - 1; i++)
                {
                    int RowIndex = dgvBills.Rows[i].Index;
                    int CurrentItem = Convert.ToInt32(dgvBills[0, RowIndex].Value);
                    if (CurrentItem <= RangeTo)
                    {
                        dgvBills.AlternatingRowsDefaultCellStyle.SelectionBackColor = Color.Cyan;
                        dgvBills.Rows[RowIndex].DefaultCellStyle.BackColor = Color.Cyan;
                    }
 
                    i++;
                }
            }
            catch (Exception)
            { }

Open in new window

LVL 8
rpkhareAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David H.H.LeeCommented:
Hi rpkhare,
You can define the selectedrowstyle in design mode instead.
eg:
<selectedrowstyle backcolor="Cyan" font-bold="true"/>  

0
rpkhareAuthor Commented:
I am using Windows Forms.
0
Jorge SanchezSoftware EngineerCommented:
Why are you using the AlternateRowsCellStyle?
I think it will work fine without it, and also without the RowIndex variable - iterator is enough:
private void ChangeRowColors()
        {
            
            try
            {
                int RangeFrom = Convert.ToInt32(txtFromPage.Text);
                int RangeTo = Convert.ToInt32(txtToPage.Text);
 
                for (int i = 0; i <= dgvBills.Rows.Count - 1; i++)
                {
                   int CurrentItem = Convert.ToInt32(dgvBills[0, i].Value);
                    if (CurrentItem <= RangeTo && CurrentItem >= RangeFrom)
                    {
               dgvBills.Rows[i].DefaultCellStyle.BackColor = Color.Cyan;
                    }
 
                    i++;
                }
            }
            catch (Exception)
            { }

Open in new window

0
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

rpkhareAuthor Commented:
Without it, it is changing only the last row color.
0
Jens FiedererTest Developer/ValidatorCommented:
You can use the CellFormatting event to specify its color.

Don't bother with the Alternating stuff, that is only two alternate between two colors to help show the rows.
        void MyDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            MyInformation key = MyDataGridView.Rows[e.RowIndex].DataBoundItem as MyInformation ;
            if (key.Normal)
            {
                e.CellStyle.BackColor = System.Drawing.SystemColors.Window;
            }
            else
            {
                e.CellStyle.BackColor = Color.LightGray;
            }
        }

Open in new window

0
rpkhareAuthor Commented:
I have two TextBoxes: From and To. When the user has entered valid range only then the method to change color is called. How to automatically fire the above code after the user has entered a valid range? I need to match values of the first column in the DataGridView.
0
Jorge SanchezSoftware EngineerCommented:
can you post your vb file, or a working solution?
0
Jens FiedererTest Developer/ValidatorCommented:
This code gets called everytime a cell is formatted, but that doesn't mean it has to DO anything.  You could set a flag when your textBoxes are entered, and use that to decide whether to do anything.

You can use

(MyDataGridView.Rows[e.RowIndex].DataBoundItem as YourTypeName).FirstColumnPropertyName

to make your decision (or access the cell directly using e.RowIndex and e.ColumnIndex.
0
rpkhareAuthor Commented:
Below is how I want to execute. Attached is the image of my Form.
       private void txtToPage_TextChanged(object sender, EventArgs e)
        {
            if (txtToPage.Text.Length > 0)
            {
                PrintRangeTo = Convert.ToInt16(txtToPage.Text);
                ChangeRowColors();
            }
            else
                PrintRangeTo = 0;
        }
 
       public void ChangeRowColors()
        {
            try
            {
                int RangeFrom = Convert.ToInt32(txtFromPage.Text);
                int RangeTo = Convert.ToInt32(txtToPage.Text);
 
                for (int i = 0; i <= dgvBills.Rows.Count - 1; i++)
                {
                    int RowIndex = dgvBills.Rows[i].Index;
                    int CurrentItem = Convert.ToInt32(dgvBills[0, RowIndex].Value);
                    if (CurrentItem <= RangeTo)
                    {
                        dgvBills.CurrentRow.Cells[0].Style.BackColor = Color.Cyan;
                    }
 
                    i++;
                }
            }
            catch (Exception)
            { }
        }

Open in new window

change-color.JPG
0
Jens FiedererTest Developer/ValidatorCommented:
Cross posted there.
Make sure to refresh your grid (to make sure formatting occurs) when the values in the textboxes are changed.

Sample Handler Attached
        void MyDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtFromPage.Text) &&
                !string.IsNullOrEmpty(txtToPage.Text))
            {
                int RangeFrom = Convert.ToInt32(txtFromPage.Text);
                int RangeTo = Convert.ToInt32(txtToPage.Text);
                int CurrentItem = Convert.ToInt32(dgvBills[0, e.RowIndex].Value);
                if (CurrentItem <= RangeTo && CurrentItem >= RangeFrom) {
                    e.CellStyle.BackColor = Color.Cyan;
                    return;
                }
            }
            e.CellStyle.BackColor = System.Drawing.SystemColors.Window;
        }

Open in new window

0
Jens FiedererTest Developer/ValidatorCommented:
And, of course, you probably want to check the value of your checkbox before checking the textboxes.
0
rpkhareAuthor Commented:
I am still not following how to call:

MyDataGridView_CellFormatting(...................)

whenever a TextBox value changes.
0
Jorge SanchezSoftware EngineerCommented:
instead of
 dgvBills.CurrentRow.Cells[0].Style.BackColor = Color.Cyan;

yo should use
 dgvBills.Rows[i].Cells[0].Style.BackColor = Color.Cyan;
0
Jens FiedererTest Developer/ValidatorCommented:
In the handler for your textbox  TextChanged event, just refresh the datagrid
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rpkhareAuthor Commented:
Thanks. I tried but it is working in a wrong way. Probably a problem in my logic. However, it is correct that color needs to be changed in the Cell_Formatting Event.

Thanks.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.