C # - DataGridView does not change DefaultCellStyle.BackColor property sent from a class to the Form

0

I'm having a question in C # regarding DataGridView.

In this scenario I have a Form where I run a Datagrid bringing information from another class. After the data is loaded by the Datagrid.Datasource the Grid is displayed on the screen without any problems. Doubt: After this task I need the rows of the data grid to be colored according to the logic of my application. In that case I create a class called AcoesGrid where it will be responsible "as it already says the name" for doing any kind of action on the Grid. In this class is the code where the rows should be colored. For this I created a property of the Data grid in the class Acoes grid: WheredoIassigntheDatagridoftheForm.IntheFormcalledViewGridImakethereferencebetweenthepropertyandthedatagrid: AfterWorkingintheGridIreturntheclasspropertytotheform,"but by displaying the Form with Grid on the screen it continues with the DataSource information but without coloring the grid." > Here is the class code for better understanding:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using ppcp_protheus.Forms;
using System.Data.Odbc;
using ppcp_protheus.Acesso_a_Dados;
using System.Drawing;
using System.Data;

namespace ppcp_protheus
{
   class clsAcoesGrid
   {
        //Propriedade criada para receber o Objeto Data Grid  do formulario Visualizar Grid.
    public DataGridView RefObjDgvPrincipal { get; set; }

    List<clsPbx> listPbx = new List<clsPbx>();

    DateTime dataBanco;
    string email;

    #region Métodos

    public  DataGridView colorirGrid(clsConexao dbCon)//, DataGridView dgvPrincipal)
    {

        //-------conectaBD.AbreXML();
        List<clsProducao> listOpsAprov = new List<clsProducao>();

        for (int i = 0; i < RefObjDgvPrincipal.Rows.Count; i++)
        {
            string operacao = RefObjDgvPrincipal[2, i].Value.ToString();
            DateTime previsao = Convert.ToDateTime(RefObjDgvPrincipal[7, i].Value.ToString() + " " + RefObjDgvPrincipal[8, i].Value.ToString());
            //DateTime previsao = Convert.ToDateTime("05/06/2018 01:52:00");
            string ordem = RefObjDgvPrincipal[10, i].Value.ToString();

            OdbcDataReader dr;
            string id = "";
            string ctde = "";
            string ctpara = "";
            string _sqlemail = "";
            string _notificado = "";

            foreach (clsPbx item in listPbx)
            {
                if (item._pbxCte == ordem)
                {
                    id = item._pbxId;
                    ctde = item._pbxCte;
                    ctpara = item._pbxCtpara;
                }
            }


            if (operacao.Contains("P"))
            {
                RefObjDgvPrincipal.Rows[i].DefaultCellStyle.BackColor = Color.Red;
            }
            else if (ordem.Substring(0, 2).Equals("AP"))
            {
                RefObjDgvPrincipal.Rows[i].DefaultCellStyle.BackColor = Color.Blue;
            }
            else if (previsao <= dataBanco)
            {
                RefObjDgvPrincipal.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;

                if (dbCon.VerificaStatusConexao() == ConnectionState.Closed)
                    dbCon.Conectar();

                _sqlemail = "SELECT TOP 1 * FROM producao_SAP_V8 WITH(NOLOCK) WHERE ordemproducao = '" + ordem + "'";
                dr = dbCon.RetornaDataReader(_sqlemail);

                if (dr.HasRows)
                {
                    _notificado = dr["notificado"].ToString();
                }


                dr.Dispose();
                dr.Close();

                if (_notificado != "1")
                {
                    clsEnviarEmail enviarEmail = new clsEnviarEmail();
                    enviarEmail.EnviaEmail(email, "Apontamento de Produção", "A Ordem de Produção," + ordem + ",ultrapassou o tempo padrão ", "");


                    try
                    {
                        if (dbCon.VerificaStatusConexao() == ConnectionState.Closed)
                            dbCon.Conectar();
                        OdbcTransaction tran = dbCon.Connection.BeginTransaction();
                        string _exclui = String.Format("UPDATE producao_SAP_V8 Set notificado = '1' WHERE ordemproducao = '{0}'", ordem);
                        OdbcCommand odbcCMD = new OdbcCommand(_exclui, dbCon.Connection);
                        odbcCMD.Transaction = tran;
                        //odbcCMD.Parameters.Add("codigomotivo",OdbcType.VarChar,10).Value = motivo;

                        if (odbcCMD.ExecuteNonQuery() >= 1)
                        {
                            tran.Commit();
                        }
                        else
                        {
                            tran.Rollback();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        dbCon.FechaBanco();
                    }
                }

                dr.Close();
                dr.Dispose();


            }
            else
            {
                RefObjDgvPrincipal.Rows[i].DefaultCellStyle.BackColor = Color.Lime;
            }

            if (ctde != "" && id != "")
            {
                if (ctpara.Equals("Gray"))
                {
                    RefObjDgvPrincipal.Rows[i].DefaultCellStyle.BackColor = Color.Gray;
                }
                else if (ctpara.Equals("White"))
                {
                    RefObjDgvPrincipal.Rows[i].DefaultCellStyle.BackColor = Color.White;
                }
                else if (ctpara.Equals("Orange"))
                {
                    RefObjDgvPrincipal.Rows[i].DefaultCellStyle.BackColor = Color.Orange;
                }
                else if (ctpara.Equals("Purple"))
                {
                    RefObjDgvPrincipal.Rows[i].DefaultCellStyle.BackColor = Color.Purple;
                }
                else if (ctpara.Equals("Brown"))
                {
                    RefObjDgvPrincipal.Rows[i].DefaultCellStyle.BackColor = Color.Brown;
                }
            }

            if (dbCon.Depto.Equals("03") && !operacao.Contains("P"))
            {
                string sqlAprov = String.Format(@"SELECT PC1.PC1_NUMOP AS ORDEM from PC1100 PC1 WITH(NOLOCK) where PC1.PC1_COD = '{0}'", ordem);
                dr = dbCon.RetornaDataReader(sqlAprov);

                while (dr.Read())
                {
                    clsProducao prod = new clsProducao();
                    prod.OrdemProducao = dr["ORDEM"].ToString();
                    listOpsAprov.Add(prod);
                }
                dr.Dispose();
                dr.Close();

                foreach (clsProducao item in listOpsAprov)
                {
                    if (item.OrdemProducao == ordem)
                    {
                        RefObjDgvPrincipal.Rows[i].DefaultCellStyle.BackColor = Color.LightBlue;
                    }
                }
            }
        }
        return RefObjDgvPrincipal;
    }
    #endregion
  }
 }

Follow the form code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ppcp_protheus.Forms;

namespace ppcp_protheus.Forms
{
   public partial class frm_Visualizar_Grid : Form
   {
     clsConexao conectaBD = new clsConexao();

    string setor;

    public frm_Visualizar_Grid()//string depto)
    {
        InitializeComponent();
        //setor = depto;
    }

    private void frm_Visualizar_Grid_Load(object sender, EventArgs e)
    {

        //Funcao do CarregarGrid
        conectaBD.AbreXML(setor);


        dgvUsinagem.AutoGenerateColumns = false;
        dgvUsinagem.DataSource = clsPPCP.painelProducao(conectaBD);

        clsAcoesGrid acoesGrid = new clsAcoesGrid();

        //Enviando Objeto dgvUsinagem para Propriedade criada na classe clsAcoesGrid
        acoesGrid.RefObjDgvPrincipal = this.dgvUsinagem;
        //clsAcoesGrid.RefObjDgvPrincipal = this.dgvUsinagem;
        acoesGrid.colorirGrid(conectaBD);
        dgvUsinagem = acoesGrid.colorirGrid(conectaBD);//, dgvUsinagem);
        //dgvUsinagem = clsAcoesGrid.colorirGrid(conectaBD);//, dgvUsinagem);
        //dgvUsinagem.RowsDefaultCellStyle.BackColor = acoesGrid.RefObjDgvPrincipal.RowsDefaultCellStyle.BackColor;

        //dgvUsinagem.RowsDefaultCellStyle.BackColor = Color.Red;

    }
    public void CarregaDepto(string depto)
    {
        setor = depto;
    }
  }
 }

I do not know what I'm doing wrong if someone can help ... I thank you for the help.
Thank you.

    
asked by anonymous 02.08.2018 / 19:45

2 answers

0

As I said in the comments, you can not really know how your program is, so I set up an example to color the lines of the DataGridView.

The logic that will be used to define the colors, you can put in the class, the data to use it should already come in the select, and not execute the select inside a loop. This will terribly hamper performance.

For example, I created the Item class, which represents each item or row of the DataGridView:

public class Item
{
    public int Id { get; set; }
    public string Descricao { get; set; }
    public decimal Valor { get; set; }
    public Color BackColor => Ativo ? (Valor > 0 ? Color.Green : Color.Blue ) : Color.Red;
    public bool Ativo { get; set; }
}

Notice that the condition for the color is already made here: If Active checks the value, if it is greater than zero, the color is green; if smaller, blue; If inactive, red.

To simulate a select in the database, I made a static method that returns a list of items:

public static class SimulaDb
{
    public static List<Item> GetItens()
    {
        List<Item> itens = new List<Item>();
        itens.Add(new Item() { Id = 1, Descricao = "Item 1", Ativo = true, Valor = 0 });
        itens.Add(new Item() { Id = 2, Descricao = "Item 2", Ativo = true, Valor = 10 });
        itens.Add(new Item() { Id = 3, Descricao = "Item 3", Ativo = true, Valor = 4 });
        itens.Add(new Item() { Id = 4, Descricao = "Item 4", Ativo = false, Valor = -10 });
        itens.Add(new Item() { Id = 5, Descricao = "Item 5", Ativo = true, Valor = -5 });
        itens.Add(new Item() { Id = 6, Descricao = "Item 6", Ativo = true, Valor = 1 });
        itens.Add(new Item() { Id = 7, Descricao = "Item 7", Ativo = false, Valor = 70 });
        itens.Add(new Item() { Id = 8, Descricao = "Item 8", Ativo = true, Valor = 50 });
        itens.Add(new Item() { Id = 9, Descricao = "Item 9", Ativo = false, Valor = 80 });
        itens.Add(new Item() { Id = 10, Descricao = "Item 10", Ativo = true, Valor = 14 });
        itens.Add(new Item() { Id = 11, Descricao = "Item 11", Ativo = true, Valor = 12 });
        itens.Add(new Item() { Id = 12, Descricao = "Item 12", Ativo = true, Valor = -1 });
        itens.Add(new Item() { Id = 13, Descricao = "Item 13", Ativo = true, Valor = 150 });


        return itens;
    }
}

Ready. Now the Form code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    List<Item> _itens;

    private void Form1_Load(object sender, EventArgs e)
    {
        _itens = SimulaDb.GetItens();
        dataGridView1.DataSource = _itens;
    }

    private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            r.DefaultCellStyle.BackColor = _itens[r.Index].BackColor;
        }
    }
}

In the Load event, I get the data from the "Database" and store it in the list.

I manipulated the event DataBindingComplete , so that when loading the data, we go through each DataGridViewRow of DataGridView and apply the color in the line.

  

Result:

I opted for the DataBindingComplete event because it only occurs once when assigning the data to the control. Other events are being fired at all times.

    
02.08.2018 / 21:48
0
 //Evento DataBidingComplete usado  quando o conteúdo dos dados de origem  forem  alterados, 
    //no caso preciso verificar as linhas "Rows" do DataGridview onde a propriedade BackColor foi alterada.
    private void dgvPrincipal_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        acoesGrid.CarregaDp(conectaBD);
        acoesGrid.colorirGrid(dgvPrincipal);

        foreach (DataGridViewRow r in dgvPrincipal.Rows)
        {
            r.DefaultCellStyle.BackColor = acoesGrid.listItens[r.Index].BackColor;
        }
    }       
    
10.08.2018 / 13:04