Question

I am trying to create a select statement in C# to check if the value inserted into a textbox (userName) is in an existing SQL database. I have a database called Employee containing a table called EVUSERS and it has a column called UName.

In my code I have a method which takes the value from a textbox called UserBox. I would like to know if there is a temporary table where the select is stored which I can compare the textbox value to.

Here is the code:

private void CheckLoginExist()
{
            String userName = UserBox.Text;

            string connectionString = @"Data Source=.\SQLEXPRESS;Database=Employee;Integrated Security=true";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand command = connection.CreateCommand())
                {

                    command.CommandText = "SELECT UName FROM EVUSERS WHERE UName = @UName";
                    command.Parameters.AddWithValue("@UName", userName);
                    connection.Open();
                    command.ExecuteNonQuery();
                    connection.Close();
                }
            }
}

I currently have a select but I am not sure how to display it and I am able to connect to the DB.

Était-ce utile?

La solution

You need ExecuteScalar, not ExecuteNonQuery

...
connection.Open();
var name = command.ExecuteScaclar().ToString();
connection.Close();

if (name != null) {
  MessageBox.Show("This name already exists");
  return;
}

Autres conseils

private void CheckLoginExist()
{
    DataTable dt = new DataTable();
    String userName = UserBox.Text;

   string connectionString = @"Data Source=.\SQLEXPRESS;Database=Employee;Integrated Security=true";
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
         SqlDataAdapter da = new SqlDataAdapter("SELECT UName FROM EVUSERS WHERE UName = '" + userName  + "'", _conn);                 
         da.Fill(dt); 
   }
}

Now you can do whatever you want to do with this DataTable.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top