Recover Sqlcommand as string

Asked

Viewed 80 times

1

I need to recover a BD information with a select and compare with what the user is typing if it is different information, I allow the Insert. If the comparison is the same I do not let insert and display error message.

Follow below what I’m trying to do:

    SqlCommand cmd = new SqlCommand(" SELECT Porta FROM Equipamento WHERE Porta = txtPorta.Text", conn);

    string portacadastrada = cmd.ToString();

    string portatentativa = Convert.ToString(txtPorta.Text);

    if (portacadastrada == portatentativa)
    {
        ShowMessage("Porta já cadastrada.");

    }
  • 1

    Because you need to convert string in string? You want to do what? Consult the database, take the returned data and compare it with what was typed? There is nothing consulted. And we probably won’t be able to help properly with just that bit. What we can already see is that this consultation is very wrong and very far from what it should be. I actually think you have a lot more problems than you think, since this code doesn’t make any sense. It seems to me that you are doing something more complex than you can do. You need to understand other more basic things before.

  • probably a form, the user fills information to register a product or whatever. and do you want to know if this same item has already been previously registered correct? when sending the form, you check your script, run a command that searches for the product name using like '%%' because it can enter the wrong product name too and it register in duplicate, but with wrong name. I think this method you use can be improved, drastically.

1 answer

1


Sqlcommand is to execute commands like Insert, Delete and Update to retrieve information you can make the following way:

//Pega a porta digitada pelo usuario
var portaDigitada = txtPorta.Text;
//Monta o comando usando DataAdapter
var comando = new SqlDataAdapter("SELECT Porta FROM Equipamento WHERE Porta 
= @porta", conn);
comando.SelectCommand.Parameters.AddWithValue("@porta", portaDigitada);
//Cria um DataTable que vai armazenar o resultado do BD
        var dt = new DataTable();
//Preenche o datatable com o resultado do bd
        comando.Fill(dt);
//Pega o Valor que esta querendo, Onde Rows[0] é o numero da linha, Considerando que esta comando traga somente uma
        string portacadastrada = dt.Rows[0]["Porta"];
  • I want exactly what Edenilson Bila said. I need to retrieve a BD information and compare it to what the user is typing before doing the Insert. If the comparison is the same I do not let enter.

  • @Denispolicarpo I fixed the method, see if the posted above suits you

  • @Edenilson Bila It worked perfectly, thank you very much! I just converted dt.Rows[0]["Port"] to string.

Browser other questions tagged

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