Compare Textbox with field in a Sqlserver table

Asked

Viewed 557 times

1

I’m stuck on this if. I want to compare my textbox with a field in a sql server, but I don’t know how to continue.

follows the code:

using (SqlConnection connection = new SqlConnection(connectionString))
{               

string queryString = "SELECT id, nome, cpf FROM " + GetType().Name + "s";

SqlCommand comand = new SqlCommand(queryString, connection);

comand.Connection.Open();

comand.ExecuteNonQuery();

****GOSTARIA de verificar se já existe esse usuário cadastrado no banco de dados****

      if (reader.Read())
            {
                if (Convert.ToInt32(reader[0]) == txtCodigo.Text)//essa condição é verdadeira, deveria executar este if, porem, cai direto no else
                {
                    AtualizarCadastro();
                }
                else
                {
                    Gravar();

                }
            } 
}

Thanks in advance!!!

1 answer

0


Try this way:

 SqlDataReader reader = comand.ExecuteReader(); //Executa o leitor
 if (reader.read())
 {
     if (txtCodigo.Text == reader[0].ToString()) //[0] é a primeira coluna que o select irá retornar, no seu caso o "id".
     {
      MessageBox.Show("Este usuário já foi cadastrado no banco de dados!"); //Só para testar.
     }
 }
  • Thanks for the help! Returned this error by including the suggested change: "An unhandled Exception of type 'System.Invalidoperationexception' occurred in System.Data.dll Additional information: Invalid read attempt when no data exists." I’m researching about.

  • Is returning this error only when if is false or in any case?

  • In any case.

  • Try adding a if (reader.read()) around the condition. I edited the answer, so there is no doubt.

  • He even read and entered the if, however I’m testing with the code "id" same as my database table, and debugging in Visual Studio, is falling into Else... What I’m not understanding, it seems that is not storing the information that comes from DB in Reader...

  • Test the values that are returning. Example: MessageBox.Show(id + 
"\n" + reader[0].ToString());

  • Can you tell me what the problem was and how you fixed it?

  • The Reader[0], was right, reading the first record... only that was not what I wanted, the right was to read the selected record in a datagridview, my logic that was flawed... I stored the selected ID in the datagridview in a property within a class in my project, there solved the problem.

Show 3 more comments

Browser other questions tagged

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