Best method for finding values in a DataTable

1

In a unit of measure register, I have to check if the unit the user wants to register, if it already exists, then since I have a DataGrid populated by a DataTable , I thought of going through DataTable and check if it already exists.

Then I made the code like this:

 //botão salvar
 private void simpleButton2_Click(object sender, EventArgs e)
    { 
        //Verifico se os dois textbox estao preenchidos
        if (textBox1.Text != string.Empty && textBox2.Text != string.Empty)
        {
            // defino minha string de filtro
            string exp = "SIGLA = " + "'" + textBox2.Text + "'";
            // Executo a busca com base no meu filtro
            DataRow[] find_sigla = dat.Select(exp);

            // se o retorno da busca for 0 faz a ação
            if (find_sigla.Count() == 0)
            {
                //Insiro o valor no banco
                Classes.Cadastro.Cadastro_estqUn cad_estqun = new Classes.Cadastro.Cadastro_estqUn();
                if (cad_estqun.cadastro_unidade(textBox1.Text, textBox2.Text) > 0)
                {
                    textBox1.Text = "";
                    textBox2.Text = "";
                }
            }
            else
            {
                MessageBox.Show("Unidade de medida já cadastrada.", "Salvar", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
    }

So I've heard that this method has lost performance, right? Does anyone have a better solution?

Thank you.

    
asked by anonymous 18.08.2016 / 04:53

1 answer

1

I would not trust what's in the DataGrid, but rather what's in the database.

A hypothetical example but applies to other real situations:

"Your system has a database server and 3 workstations.Your user opened this screen and had 5 units of measurements, but he went to lunch.While he had lunch, someone registered the unit of measurement that he was going to register. duplicate in the database if it registers after lunch because the DataGrid is outdated. "

In this class Cadastro_estqUn make an implementation that checks the database if the record with the description already exists. It would look something like this:

public bool UnidadeMedidaUnica(string nome) 
{
  string sql = "SELECT COUNT(*) FROM tbUnidadeMedida WHERE unidade_nome = @nome";
  SqlCommand cmd = new SqlComman(sql, connectionString);
  cmd.Parameters.AddWithValue("@nome", nome);
  SqlDataReader mySqlDataReader = cmd.ExecuteReader();
  int qtde = (int)cmd.ExecuteScalar();
  return qtde == 0;

}

To improve, you can add a "unique index", which will ensure that even SQL statements triggered directly in the database duplicate records.

CREATE UNIQUE INDEX idx_unidade_nome ON tbUnidadesMedida(unidade_nome)
    
31.08.2016 / 02:20