user2491469 user2491469 - 1 year ago 50
SQL Question

SQL - Select value from specific column of the table

I am trying to make a c# windows forms project which would select a value from specific column of the table.

I have a table called "Person" which looks like this:

ID | Name | Job
1 | Peter| Mechanic
2 | John | Pilot

This is what I wanna do. If I write a name into the first textbox, I want to get a job of that person in the second textbox upon button click.

So let's say I write the name "John" into the textbox. I click the button and the program shows the word "pilot" in the second textbox.

How can I do that?

Answer Source

If you know the database that you are targeting, this is going to be a very straightforward SELECT query executing using a basic SqlConnection object (assuming a SQL Server database) :

using(var connection = new SqlConnection("{your-connection-string}"))
     // Build your query
     var query = "SELECT TOP 1 Job From YourTable WHERE Name = @Name";
     using(var command = new SqlCommand(query,connection))
          // Add your parameter to perform the query
          command.Parameters.AddWithValue("@Name", NameTextBox.Text);

          // Execute the query and retrieve the job
          var job = Convert.ToString(command.ExecuteScalar());
               // No job was found, handle accordingly
               // Set the job in the appropriate area
               JobTextBox.Text = job;

You would include this or similar code within your event to trigger your query (i.e. once you have your name populated, once you click your button, etc).