Retrieve Data from a SQL Server Database in C#
When working with a database table containing columns such as firstname, Lastname, and age, retrieving specific data values based on user input can be essential. In this scenario, you have three textboxes in your C# Windows application and have established a connection to a SQL Server database.
To retrieve all other details corresponding to a given firstname value, a parametrized query approach is recommended for security reasons. Here's how you can achieve this:
public Person SomeMethod(string fName) { var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString(); Person matchingPerson = new Person(); using (SqlConnection myConnection = new SqlConnection(con)) { string oString = "Select * from Employees where FirstName=@Fname"; SqlCommand oCmd = new SqlCommand(oString, myConnection); oCmd.Parameters.AddWithValue("@Fname", fName); myConnection.Open(); using (SqlDataReader oReader = oCmd.ExecuteReader()) { while (oReader.Read()) { matchingPerson.firstName = oReader["FirstName"].ToString(); matchingPerson.lastName = oReader["LastName"].ToString(); } myConnection.Close(); } } return matchingPerson; }
Explanation:
Usage:
To use this method, you can call it like this:
Person x = SomeMethod("John");
Once you have the data in the Person object, you can assign the values to the textboxes in your application:
txtLastName.Text = x.LastName;
This approach allows you to retrieve all the other details related to a specific firstname value from the database and display them in the corresponding textboxes.
The above is the detailed content of How to Retrieve Specific Data from a SQL Server Database Using C#?. For more information, please follow other related articles on the PHP Chinese website!