Home >Database >Mysql Tutorial >How to Retrieve and Display SQL Server Data in a C# Windows Application?
Retrieve Data from SQL Server in C#
This guide will assist you in retrieving data from a SQL Server database using C# and a Windows application.
Establishing Database Connectivity
You have successfully established a connection to your SQL Server instance using the following code:
SqlConnection con = new SqlConnection("Data Source = .; Initial Catalog = domain; Integrated Security = True");
Retrieving Data
To retrieve data based on a value entered in a textbox (e.g., textbox1), you need to modify your code:
cmd.CommandText = "SELECT * FROM tablename WHERE firstname = @firstname";
Use parameterization to ensure the security of your query:
SqlParameter param = new SqlParameter("@firstname", SqlDbType.VarChar, 50); param.Value = textbox1.Text; cmd.Parameters.Add(param);
Populating Textboxes
You'd like to fill other textboxes with data based on the retrieved values. Here's a way to achieve this:
Create a class to represent a person (e.g., Person):
public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } }
Then, retrieve a person from the database using a parameterized method:
public Person GetPerson(string firstName) { string connectionString = "Data Source = .; Initial Catalog = domain; Integrated Security = True"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand("SELECT * FROM tablename WHERE firstname = @firstname", connection); command.Parameters.Add(new SqlParameter("@firstname", firstName)); connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { Person person = new Person { FirstName = reader["firstname"].ToString(), LastName = reader["lastname"].ToString(), Age = (int)reader["age"] }; return person; } else { return null; // No matching person found } } } }
Finally, populate your textboxes using the Person object:
textbox2.Text = person.LastName; // Replace "textbox2" with the name of your textbox textbox3.Text = person.Age.ToString(); // Replace "textbox3" with the name of your textbox
The above is the detailed content of How to Retrieve and Display SQL Server Data in a C# Windows Application?. For more information, please follow other related articles on the PHP Chinese website!