Pergunta

Eu criei um aplicativo que exibe os registros do banco de dados na janela e verifica o banco de dados para novos registros a cada dois segundos. O problema é que a janela pisca cada vez que verifico novos registros e quero corrigi -lo. Eu tentei comparar o antigo Datatable com o novo e atualizar apenas se eles forem diferentes. Alguém sabe qual é a melhor prática para esses casos? Eu tentei fazer isso da seguinte maneira, mas não funciona:

private bool GetBelongingMessages()
        {
            bool result = false;
            DataTable dtTemp = OleDbWorks.GetBelongingMessages(currentCallID);
            if(dtTemp != dtMessages)
            {
                dtMessages = dtTemp;
                result = true;
            }
            else
            {
                result = false;
            }
            return result;
        }
Foi útil?

Solução

Primeiro, é importante reconhecer que o que você está comparando em seu código é o referências dos dados de dados, não o conteúdo dos dados de dados. Para determinar se ambos os dados têm o mesmo conteúdo, você precisará percorrer todas as linhas e colunas e ver se são iguais:

//This assumes the datatables have the same schema...
        public bool DatatablesAreSame(DataTable t1, DataTable t2) {         
            if (t1.Rows.Count != t2.Rows.Count)
                return false;

            foreach (DataColumn dc in t1.Columns) {
                for (int i = 0; i < t1.Rows.Count; i++) {
                    if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) {
                        return false;
                    }
                }
            }
            return true;
        }

Outras dicas

Eu tenho tentado encontrar uma maneira de fazer uma comparação de dados por um tempo e acabei escrevendo minha própria função, eis o que eu consegui:

bool tablesAreIdentical = true;

// loop through first table
foreach (DataRow row in firstTable.Rows)
{
    foundIdenticalRow = false;

    // loop through tempTable to find an identical row
    foreach (DataRow tempRow in tempTable.Rows)
    {
        allFieldsAreIdentical = true;

        // compare fields, if any fields are different move on to next row in tempTable
        for (int i = 0; i < row.ItemArray.Length && allFieldsAreIdentical; i++)
        {
            if (!row[i].Equals(tempRow[i]))
            {
                allFieldsAreIdentical = false;
            }
        }

        // if an identical row is found, remove this row from tempTable 
        //  (in case of duplicated row exist in firstTable, so tempTable needs
        //   to have the same number of duplicated rows to be considered equivalent)
        // and move on to next row in firstTable
        if (allFieldsAreIdentical)
        {
            tempTable.Rows.Remove(tempRow);
            foundIdenticalRow = true;
            break;
        }
    }
    // if no identical row is found for current row in firstTable, 
    // the two tables are different
    if (!foundIdenticalRow)
    {
        tablesAreIdentical = false;
        break;
    }
}

return tablesAreIdentical;

Comparado à solução de Dave Markle, a mina trata duas tabela com os mesmos registros, mas em diferentes ordens idênticas. Espero que isso ajude quem tropeça neste tópico novamente.

Você precisa lançar objetos t1.rows [i] [dc.columnname] e t1.rows [i] [dc.columnname] Caso contrário, a instrução t1.rows [i] [dc.columnname]! = T2.rows [i] [dc.columnname] é sempre verdadeiro. Eu modifiquei o código da seguinte maneira:

for(int i = 0; i < t1.Rows.Count; i++)
            {
                if((string)t1.Rows[i][1] != (string)t2.Rows[i][1])
                    return false;
            }

E funciona, mas não é uma solução elegante.

 public Boolean CompareDataTables(DataTable table1, DataTable table2)
   {
       bool flag = true;
       DataRow[] row3 = table2.Select();
       int i = 0;// row3.Length;
       if (table1.Rows.Count == table2.Rows.Count)
       {
           foreach (DataRow row1 in table1.Rows)
           {
               if (!row1.ItemArray.SequenceEqual(row3[i].ItemArray))
               {
                   flag = false;
                   break;
               }
               i++;
           }

       }
       else
       {
           flag = false;
       }
       return flag;
   }

// Aqui esta função devolverá a booleano, pois o resultado retornará verdadeiro se ambos forem o mesmo retornar

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top