Duvida If / Else

27/08/2013

0

Pessoal estou fazendo uma tabela via string com concatenação.
Mas percebi, que algumas condições, estão sendo ignoradas, veja o trecho do código.
Em uma parte do código ele ignora meu if e vai direto para o else.


 else if (id_projeto == 2)
            {

                var drOcorrencias = clsLojas.retornaQuery("SELECT * FROM OCORRENCIAS where id_loja=" + id_loja + "");

                if (drOcorrencias == null) //ESSE IF E IGNORADO E VAI DIRETO PARA O ELSE, O QUE DEVO ESTAR FAZENDO DE ERRADO..
                {
                    tablestring2 = tablestring2 + "<table align='center' border='1' bordercolor='#666666' bordercolordark='#000000' width='100%' style='font-size:12px'>";
                    var drItens = clsLojas.retornaQuery("SELECT * FROM ITENS where id_projeto = 2 and id_canal = " + id_canal + " order by id_item");
                    while (drItens.Read())
                    {
                        tablestring2 = tablestring2 + "<tr bgcolor=\"\" onMouseOver=\"javascript:this.style.backgroundColor='#FFCC66';\" onMouseOut=\"javascript:this.style.backgroundColor='';\">";
                        tablestring2 = tablestring2 + "<td style='padding:25px;'> " + drItens["ds_item"] + "</td>";
                        tablestring2 = tablestring2 + "<td>";
                        tablestring2 = tablestring2 + "<table width='100%' border='0'>";
                        var drResp = clsLojas.retornaQuery("SELECT * FROM RESP_2 where id_item = " + drItens["id_item"].ToString().Trim() + " and id_subitem = 0 and id_loja = " + id_loja.ToString().Trim() + " ");
                        while (drResp.Read())
                        {
                            tablestring2 = tablestring2 + "<tr><td colspan='2' style='text-align:center;'>";
                            tablestring2 = tablestring2 + "<hr />";
                            tablestring2 = tablestring2 + " " + drResp["subresp"] + " ";
                            tablestring2 = tablestring2 + "<hr />";
                            //obs = (string)drResp["obs"];
                        }
                        tablestring2 = tablestring2 + "</td></tr>";
                        var drSubItens = clsLojas.retornaQuery("SELECT * FROM subitens where id_item = " + drItens["id_item"].ToString().Trim() + " AND ID_SUBITEM IN (SELECT ID_SUBITEM FROM UNI_TB_RESP_2 where id_item = " + drItens["id_item"] + " and id_loja = " + id_loja + " AND SUBRESP <> '') order by id_subitem");
                        while (drSubItens.Read())
                        {
                            tablestring2 = tablestring2 + "<tr><td style='text-align:center;'><hr />";
                            if (drSubItens["tipo"].ToString().Trim() == "D" || drSubItens["tipo"].ToString().Trim() == "N" || drSubItens["tipo"].ToString().Trim() == "I" || drSubItens["tipo"].ToString().Trim() == "S" ||
                                drSubItens["tipo"].ToString().Trim() == "")
                            {
                                tablestring2 = tablestring2 + " " + drSubItens["ds_subitem"] + ":";
                                
                            }

                            var drResp2 = clsLojas.retornaQuery("SELECT * FROM RESP_2 where id_item = " + drItens["id_item"].ToString().Trim() + " and id_subitem = " + drSubItens["id_subitem"].ToString().Trim() + " and id_loja = " + id_loja + " ");
                            while (drResp2.Read())
                            {

                                tablestring2 = tablestring2 + " " + drResp2["subresp"] + " ";
                                //drResp2["obs"].ToString();
                                drResp2.Close();
                            }

                            tablestring2 = tablestring2 + " </td></tr>";
                            tablestring2 = tablestring2 + "<tr><td colspan='2'><hr /></td></tr>";
                        }
                        drItens.Close();
                            drResp.Close();
                            drSubItens.Close();
                            
                        tablestring2 = tablestring2 + "</td></tr>";
                        tablestring2 = tablestring2 + "</table>";
                        divRelatorio.InnerHtml = tablestring2;
                    }  
                }
                else
           
                {
                    while (drOcorrencias.Read())
                    {
                        tablestring2 = tablestring2 + "<table align='center' border='1' bordercolor='#666666' bordercolordark='#000000' width='100%' style='font-size:12px'>";
                        tablestring2 = tablestring2 + "<tr><td align='center'><font color='red'><strong>OCORRENCIA</strong></font></td></tr>";
                        tablestring2 = tablestring2 + "<tr><td align='center'> <br />" + drOcorrencias["obs"] + "<br /> </td></tr>";
                        tablestring2 = tablestring2 + "<tr><td align='center'>Responsável: " + drOcorrencias["responsavel"] + "</td></tr>";
                        tablestring2 = tablestring2 + "</table>";
                        divRelatorio.InnerHtml = tablestring2;
                        
                    }
                }
                drOcorrencias.Close();
            }


Obridado Galera
Rodrigolima

Rodrigolima

Responder

Posts

27/08/2013

Pjava

É bem provável que ocorrencia não esteja null. Coloque um Break Point antes do IF e teste a variável ocorrência e veja se tem algo. Lembrando que vazia ("") não é NULL.
Responder

27/08/2013

Tiago

Recomendo utilizar o Debug e verifique o valor atual do objeto... bem lembrado pjava, acredito que resolve.
Responder

27/08/2013

Rodrigolima

Isso mesmo amigo, resolvi fazendo essa decisão
if (drOcorrencias.HasRows == false)
{

}

obrigado amigos.
Responder

28/08/2013

Tiago

Por nada Rodrigo, boa sorte na programação ai!
Responder

28/08/2013

Clayton Silva

Isso mesmo amigo, resolvi fazendo essa decisão
if (drOcorrencias.HasRows == false)
{

}


if já procura o resultado boolean, não precisa fazer esta comparação.

if (drOcorrencias.HasRows)

já resolve, caso queria negativo use uma exclamação antes.

if (!drOcorrencias.HasRows)
Responder

28/08/2013

Rodrigolima

Obrigado amigo mas uma vez, todo dia eu aprendendo, mais uma.
Fiz dessa maneira, uma pratica mais correta.

Obrigado.
Responder

28/08/2013

Clayton Silva

Obrigado amigo mas uma vez, todo dia eu aprendendo, mais uma.
Fiz dessa maneira, uma pratica mais correta.

Obrigado.

Tentamos ajudar sempre, mais umas dicas que vi em seu código.

comece a usar parâmetros, evite concatenar strings nas querys pois deixa o código propenso a invasão.

Evite concatenar strings usando +, é um procedimento que gasta muita memória e usado várias vezes, como em seu código, não é recomendado. Para isto use um stringbuilder.
Responder

28/08/2013

Tiago


Tentamos ajudar sempre, mais umas dicas que vi em seu código.

comece a usar parâmetros, evite concatenar strings nas querys pois deixa o código propenso a invasão.

Evite concatenar strings usando +, é um procedimento que gasta muita memória e usado várias vezes, como em seu código, não é recomendado. Para isto use um stringbuilder.



Essa observação é muito importante, afinal usar parâmetros é uma boa prática e evita erros de SQLINJECTION... concatenar strings é uma má prática, se bem que ainda vemos em exemplos de faculdade ou coisa e tipo... mas de como não fazer hehe.
Responder

28/08/2013

Joel Rodrigues

Como a dúvida foi resolvida, estou marcando o tópico como Concluído.
Responder

10/09/2013

Rodrigolima

Pessoal usei fiz update no meu codigo, usei paramentros e o StringBuilder sb = new StringBuider();
Obrigado Pessoal
Responder

10/09/2013

Clayton Silva

Pessoal usei fiz update no meu codigo, usei paramentros e o StringBuilder sb = new StringBuider();
Obrigado Pessoal


Meus parabéns.
Responder

10/09/2013

Rodrigo Odasaki

else if (id_projeto == 2)

Coloca um enum, seu código ficara mais entendível.
Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar