2013-04-30 3 views
0

en utilisant ce code mais en donnant la référence d'objet d'erreur n'est pas défini sur l'instance de l'objet.comment modifier la couleur des lignes en fonction de la valeur de la colonne

using (SqlConnection sqlConn = new SqlConnection("Data Source=OMKAR-PC;Initial Catalog=omkar;Persist Security Info=True;User ID=sa;Password=omkar;Pooling=False")) 
    { 
     sqlConn.Open(); 

     using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM customer ", sqlConn)) 
     { 
      DataTable t = new DataTable(); 
      a.Fill(t); 
      dataGridView1.DataSource = t; 

      this.dataGridView1.CellFormatting += 
new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting); 


     foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
      try 
      { 
      string CNumColour = dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString(); 
      if (CNumColour != null) 
      { 
       foreach (DataGridViewCell cells in row.Cells) 
       { 
       if (CNumColour == "yes") 
        { 
        cells.Style.ForeColor = Color.Pink; 
        } 
        else if (CNumColour == "no") 
        { 
        cells.Style.ForeColor = Color.Red; 
        } 
       } 
       } 
      } 
     catch (System.Exception ex) 
     { 

     } 
     } 
     sqlConn.Close(); 
    } 
+1

Quelle ligne donne l'erreur? – Aditi

Répondre

1

Vérifiez cette ligne.

string CNumColour = dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString(); 

dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString(); 

donne une valeur nulle.

Si possible, essayez en donnant l'index de la ligne actuelle comme:

dataGridView1.Rows[row.RowIndex].Cells[0].FormattedValue.ToString(); 

Espérons son utile.

Questions connexes