C# - Datagridview does not change Defaultcellstyle.Backcolor property sent from a class to Form

Asked

Viewed 146 times

0

I have 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 Datagrid.Datasource the Grid is displayed on the screen smoothly. Doubt: After this task I need the data grid rows to be colored according to the logic of my application. In this case I create a class called Acoesgrid where she will be responsible " as the name already says" 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 Data grid property in the Acoes grid class: inserir a descrição da imagem aqui Where I assign the Form Data Grid. In the form called View Grid I make the reference between the property and the data grid: inserir a descrição da imagem aqui After Working on the Grid I return the class property to the form, "but by showing the Form with Grid on the screen it continues with the Datasource information but without coloring the grid."
Follow 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 code of the Form:

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 don’t know what I’m doing wrong if anyone can help... I leave my thanks for the help.
Thank you.

  • Apparently you have created a method that returns another Datagridview, calls the method but does not apply the return anywhere. Also the code is very confusing...

  • by the way, you have another question that was not solved or you did not mark as answer: https://answall.com/questions/307928/chamar-form2-com-circular-progress-bar-enquanto-outra-a%C3%A7%C3%A3o-%C3%A9-executed-c

  • Sorry I thought I had already selected the question: https://answall.com/questions/307928/chamar-form2-com-circular-progress-bar-enquanto-outra-a%C3%A7%C3%A3o-%C3%A9-executed-c

  • the Return of this method: public Datagridview colorirGrid(clsConexao dbCon) { } Return Refobjdgvprincipal; "Wasn’t to return the datagrid to the form? form code: dgvUsinagem = acoesGrid.colorirGrid(conectaBD);?

  • if it’s returning, it should be assigned, something like dgvUsinagem = acoesGrid.colorirGrid(conectaBD); but it makes no sense to do this... try to separate better what each method does... and return the logic of colors already in the select of the data

  • How ? can you give me an example? return the colors of the datagril property to another datagrid?

  • what is clsProducao and clsPbx ? What is the logic for applying colors ?

  • The logic for applying the colors is in nos if / Else for example the operation contain substring "P" means that in my base it brings an operation of Equipment Shutdown.

  • Then the line will be colored by one color. If the construction forecast of the part exceeds the date bank fills the line with another color and so on, there are several in the block of conium. clsProduction brings a list of Ops= production order with taking notes. Take me awayOur doubt is right I do the property of type data grid and send the datagrid to another class and then return the way I did or did not exist better applications?

  • see if the answer helps...

Show 5 more comments

2 answers

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;
        }
    }       

0


As I said in the comments can not know very well how your program is, so I set an example to color the lines of Datagridview.

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

For example, I created the Item class, which represents each Datagridview item or line:

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; }
}

Note that here is already made the condition for the color: If Active checks the value, if it is greater than zero, the color is green; if it is 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 Load Event, I receive data from the "Database" and store 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 on the line.

Upshot:

inserir a descrição da imagem aqui


I chose the event DataBindingComplete because this only occurs once when assigning the data to the control. Other events are being triggered at all times.

  • 1

    Using the Databindingcomplete event as an example that our friend Rovann proposed. I was able to solve the problem. I leave here the code I used and my thanks for all the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.