• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1944
  • Last Modified:

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

0
rpkhare
Asked:
rpkhare
  • 6
  • 5
  • 3
  • +1
1 Solution
 
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
 
jorgesv13Commented:
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
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
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
 
jorgesv13Commented:
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
 
jorgesv13Commented:
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 6
  • 5
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now