Noa Hauswirth
Noa Hauswirth

Reputation: 21

How can i read out the Id with the name

I want to code a little program taht should read out the id from a database. you only got the name that you type in a textbox and that it should search the id from the name and put it out.

I have tried to change the strings and the sql statement

private void button2_Click(object sender, EventArgs e)
        {
            SqlConnection con1 = new SqlConnection(conString);
            con1.Open();
            if (con1.State == System.Data.ConnectionState.Open)
            {
                string nameInput = txtNameInput.Text;
                string query = "SELECT id " + "FROM test" + "WHERE name LIKE 
                '" + nameInput + "'";
                txtIdOutput.Text = query;
                SqlCommand cmd = new SqlCommand(query, con1);
            }
        }

when I put in a name and press on the button, i will see the sql statement in the second textbox but not the id. i want the id

Upvotes: 1

Views: 355

Answers (1)

nvoigt
nvoigt

Reputation: 77324

Not the perfect implementation, but it should get you started:

txtIdOutput.Text = string.Empty;

using(var connection = new SqlConnection(conString))
{
    connection.Open();

    using(var command = connection.CreateCommand())
    {
         command.CommandText = "SELECT id FROM test WHERE name LIKE @name";
         command.Parameters.AddWithValue("@name", txtNameInput.Text);

          using(var reader = command.ExecuteReader())
          {
               while(reader.Read())
               {
                   txtIdOutput.Text += reader.GetValue(0).ToString();
               }
          }
    }
}

Upvotes: 2

Related Questions