Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# Gridview Color Application , +
I have stuck in a weird problem... I have a girdview to display stock data. In this stock data I have to highlight NEGATIVE stock records in YELLOW.
 
I did some google search for this and found a solution, which worked fine when I set this form as default form of application through program.cs file. But whenever I invoke the form through a MASTER form (i.e. MDI Parent), code for changing row color does not work. I debugged the code and found that program go through the logic properly but does not change row color.
 
Below is the code which I have written...
 
private void LoadData()
        {
            getLotID_frmLotReport.LotID__frmLotReport = 0; //Table unique ID to fetch records
            string sql = "Select LotID, LotNumber as 'Lot Number', LotName as 'Lot Name', Size_ as Size, convert(varchar(10),LotCreateDate,105) as 'Create Date', round(TotalLotPurchased,2) as 'Lot Purchased', round(TotalLotSold,2) as 'Lot Sold', isnull(round(TotalLotPurchased,2),0)-isnull(round(TotalLotSold,2),0) as 'Total Stock' from dbo.Stock_Lot";
            clsPurchase obj = new clsPurchase(); // Class to execute select query
            DataSet ds = obj.GetData(sql); // function in above class to execute query & get data in dataset
            try
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    BindingSource bsource = new BindingSource();
 
                    DataGridViewLinkColumn dl = new DataGridViewLinkColumn();
                    dl.DataPropertyName = "Lot Number";
                    dl.Name = "Lot Number";
                    dataGridView1.Columns.Add(dl);
                    //this.dataGridView1.Columns["Lot Number"].SortMode = DataGridViewColumnSortMode.Automatic;
                    //this.dataGridView1.Columns["Lot Name"].SortMode=DataGridViewColumnSortMode.NotSortable;
                    bsource.DataSource = ds.Tables[0];
                    dataGridView1.DataSource = bsource;
                    this.dataGridView1.Columns["LotID"].Visible = false;
                    this.dataGridView1.DefaultCellStyle.Font = new Font("Tahoma", 9);
                    this.dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Tahoma", 9);
 
                   
//***************** NOW BELOW IS THE CODE TO CHANGE COLOR OF SPECIFIC ROWS TO YELLOW ********//
//***************** THIS CODE WORKS IF THIS FORM IS DEFAULT FORM AND NOT INVOKED THROUGH master page **************** //                    
                    string RowIndex = "";
                    string[] RowIndex_arr;
                    
                    clsConnection objConn = new clsConnection();
                    string conn = objConn.ConnDB();
                    string sql1 = "Select isnull(round(TotalLotPurchased,1),0)-isnull(round(TotalLotSold,1),0) as 'Total Stock' from dbo.Stock_Lot";
                    SqlConnection connection = new SqlConnection(conn);
                    connection.Open();
                    SqlCommand cmd = new SqlCommand(sql1, connection);
                    SqlDataReader rd = cmd.ExecuteReader();
                    int i = 0;
                    if (rd.HasRows)
                    {
                        while (rd.Read())
                        {
                            if (Convert.ToDouble(rd["Total Stock"]) <= 0)
                            {
                                RowIndex = RowIndex + i.ToString() + ",";
                            }
                            i = i + 1;
                        }
                    }
                    connection.Close();
                    connection.Dispose();
                    RowIndex = RowIndex.Remove(RowIndex.Length - 1);
                    RowIndex_arr = RowIndex.Split(',');
 
                    foreach (string s in RowIndex_arr)
                    {
                        if (s != "")
                        {
                                    this.dataGridView1.Rows[Convert.ToInt32(s)].DefaultCellStyle.BackColor = Color.Yellow;
                        }
                    }
                    
                }
                else
                {
                    MessageBox.Show("No Data found!");
                    this.Close();
 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
 
        }

 
If possible try to run this code at your end by making this form default form as well as invoke through MASTER page, or provide me another alternative if u have already developed something like that. Please let me know if u don't understand anything from my code...
 
This task is imperative for the completion of project and I have already crossed a deadline. This is a show Stopper feature of application.
 
Any help would be GREATLY APPRECIATED!
 
Thanks and regards,
 
SAM D
Posted 6-Apr-13 3:14am
sam7one513

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

add DataBindingComplete event of dataGridView1 to change color..
to know more about DataBindingComplete event of dataGridView check following link
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.databindingcomplete.aspx[^]
try this code
private void LoadData()
        {
            getLotID_frmLotReport.LotID__frmLotReport = 0; //Table unique ID to fetch records
            string sql = "Select LotID, LotNumber as 'Lot Number', LotName as 'Lot Name', Size_ as Size, convert(varchar(10),LotCreateDate,105) as 'Create Date', round(TotalLotPurchased,2) as 'Lot Purchased', round(TotalLotSold,2) as 'Lot Sold', isnull(round(TotalLotPurchased,2),0)-isnull(round(TotalLotSold,2),0) as 'Total Stock' from dbo.Stock_Lot";
            clsPurchase obj = new clsPurchase(); // Class to execute select query
            DataSet ds = obj.GetData(sql); // function in above class to execute query & get data in dataset
            try
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    BindingSource bsource = new BindingSource();
 
                    DataGridViewLinkColumn dl = new DataGridViewLinkColumn();
                    dl.DataPropertyName = "Lot Number";
                    dl.Name = "Lot Number";
                    dataGridView1.Columns.Add(dl);
                    //this.dataGridView1.Columns["Lot Number"].SortMode = DataGridViewColumnSortMode.Automatic;
                    //this.dataGridView1.Columns["Lot Name"].SortMode=DataGridViewColumnSortMode.NotSortable;
                    bsource.DataSource = ds.Tables[0];
                    dataGridView1.DataSource = bsource;
                    this.dataGridView1.Columns["LotID"].Visible = false;
                    this.dataGridView1.DefaultCellStyle.Font = new Font("Tahoma", 9);
                    this.dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Tahoma", 9);
 

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
 
        }
 
	private void dataGridView1_DataBindingComplete(object sender,DataGridViewBindingCompleteEventArgs e)
        {
            DataGridViewCellStyle myColor= dataGridView1.DefaultCellStyle.Clone();
            myColor.BackColor = Color.Yellow;
 
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if(!row.IsNewRow)
                    {
                        if (row.Cells["Total Stock"].Value.ToString() != "")
                        {
                            row.DefaultCellStyle = myColor;
                        }
                    }
                }
            
        }
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 390
1 Jochen Arndt 150
2 Richard MacCutchan 135
3 DamithSL 95
4 Garth J Lancaster 90
0 OriginalGriff 6,045
1 DamithSL 4,601
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,260


Advertise | Privacy | Mobile
Web04 | 2.8.141220.1 | Last Updated 7 Apr 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100