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!!!
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.
– Caio
Is returning this error only when if is false or in any case?
– Francisco
In any case.
– Caio
Try adding a
if (reader.read())
around the condition. I edited the answer, so there is no doubt.– Francisco
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...
– Caio
Test the values that are returning. Example:
MessageBox.Show(id + 
"\n" + reader[0].ToString());
– Francisco
Can you tell me what the problem was and how you fixed it?
– Francisco
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.
– Caio