Click here to Skip to main content
15,887,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C#
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
       {
           try
           {

               if ((this.dataGridView1.Columns[e.ColumnIndex].Name == "STATUS"))
               {
                   if (Convert.ToString(e.Value) == "Cleared")
                   {


                       e.CellStyle.BackColor = Color.YellowGreen;
                       e.CellStyle.ForeColor = Color.Blue;


                   }

               }

           }

           catch (Exception ex1)
           {
               MessageBox.Show(ex1.ToString());

           }




           }



I have a datagridView1 with column UNITSLNO and column STATUS . the given code makes the background yellowgreen and foreground Blue , of the cells in column STATUS where value of the cell is "Cleared". now i want to change the foreground and background of the cells of the same row(row in which Column STATUS have value "Cleared") and column UNITSLNO of the datagridview1.

I tried as below but did not get the result

C#
try
          {

              if ((this.dataGridView1.Columns[e.ColumnIndex].Name == "STATUS"))
              {


                  if (Convert.ToString(e.Value) == "Cleared")
                  {
                      DataGridViewCellStyle cs = new DataGridViewCellStyle();
                      cs.ForeColor = Color.Red;
                      cs.BackColor = Color.Yellow;

                      e.CellStyle.BackColor = Color.YellowGreen;
                      e.CellStyle.ForeColor = Color.Blue;
                      e.FormattingApplied = true;
                      dataGridView1.Rows[e.RowIndex].Cells["UNITSLNO"].Style = cs;

                  }


              }


          }

          catch (Exception ex1)
          {
              MessageBox.Show(ex1.ToString());

          }


in fact this code made all the cells in the column UNITSLNO with the chosen foreground and background rather than intended cell ie(Cells in the rows where column STATUS have values "Cleared");tried many other ways even with foreach statement and for statement; nothing worked fine which throws exception like IndexOutofRange. please somebody help me; thanks in advance.
Posted
Updated 12-Sep-11 4:51am
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900