[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Change color of some rows in DataGridView

Posted on 2008-11-08
16
Medium Priority
?
1,936 Views
Last Modified: 2013-12-17
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
Comment
Question by:rpkhare
  • 6
  • 5
  • 3
  • +1
15 Comments
 
LVL 29

Expert Comment

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

0
 
LVL 8

Author Comment

by:rpkhare
ID: 22913322
I am using Windows Forms.
0
 
LVL 8

Expert Comment

by:jorgesv13
ID: 22913940
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
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 
LVL 8

Author Comment

by:rpkhare
ID: 22915073
Without it, it is changing only the last row color.
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 22930140
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
 
LVL 8

Author Comment

by:rpkhare
ID: 22930261
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
 
LVL 8

Expert Comment

by:jorgesv13
ID: 22930342
can you post your vb file, or a working solution?
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 22930436
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
 
LVL 8

Author Comment

by:rpkhare
ID: 22930484
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
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 22930645
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
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 22930840
And, of course, you probably want to check the value of your checkbox before checking the textboxes.
0
 
LVL 8

Author Comment

by:rpkhare
ID: 22930913
I am still not following how to call:

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

whenever a TextBox value changes.
0
 
LVL 8

Expert Comment

by:jorgesv13
ID: 22930994
instead of
 dgvBills.CurrentRow.Cells[0].Style.BackColor = Color.Cyan;

yo should use
 dgvBills.Rows[i].Cells[0].Style.BackColor = Color.Cyan;
0
 
LVL 23

Accepted Solution

by:
Jens Fiederer earned 750 total points
ID: 22931051
In the handler for your textbox  TextChanged event, just refresh the datagrid
0
 
LVL 8

Author Closing Comment

by:rpkhare
ID: 31514691
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

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Integration Management Part 2
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses
Course of the Month17 days, 18 hours left to enroll

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question