When clicking the button check whether the value of the textbox contains in a table column

Asked

Viewed 92 times

1

How can I check the textbox if it contains this value within the table in the Database column when clicking the button?

I made this code, but I didn’t succeed:

SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["conString"].ConnectionString);

 private void button2_Click(object sender, EventArgs e)
    {
            try
        {
            SqlCommand cmd = new SqlCommand($"SELECT * FROM Alunos WHERE Numero ={txtNome.Text.Text}", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            int j = ds.Tables[0].Rows.Count;
            if (j == 0)
            {
                MessageBox.Show("word" + txtNome.Text + "already exists!");
                ds.Clear();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
}
  • You tested the code?

  • The code is incomplete, can you give us more information? Your question is in the query? if yes, you can tell us more about its structure?

  • I put the whole code.

  • @Viniciusbittencourt The Code showed some error?

  • Nothing happens when I click the button.

  • I put a value I didn’t have in the Column and Messagebox appeared. How do I do it backwards?

  • You’re not opening your connection (conn.Open();) and your check is reversed. You have to check if there is any word, ie if the rowcount is greater than 0.

Show 2 more comments

1 answer

1


The problem in the code is found in your Count

int j = ds.Tables[0].Rows.Count;
if (j == 0)
{
  MessageBox.Show("word" + txtNome.Text + "already exists!");
  ds.Clear();
}

This means that the message will be displayed only if the number of values is 0, that is, if it does not exist.

Just change

if (j == 0)

for

if (j > 0)

Thus, if any value exists (more than one line), the message will be displayed!

Browser other questions tagged

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