C#中以一个文本框内容作为数据库查询条件并把结果输出到另一个文本框中
时间: 2024-03-11 17:49:38 浏览: 20
你可以使用 ADO.NET 提供的 SQLDataReader 类来按条件查询数据库,并将查询结果输出到另一个 TextBox 控件中。以下是一个示例代码:
```csharp
string connectionString = "Data Source=YOUR_SERVER_NAME;Initial Catalog=YOUR_DATABASE_NAME;Integrated Security=True";
string query = "SELECT * FROM YOUR_TABLE_NAME WHERE YOUR_COLUMN_NAME = @param";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add("@param", SqlDbType.NVarChar).Value = textBox1.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
textBox2.Text = reader["YOUR_RESULT_COLUMN_NAME"].ToString();
}
}
else
{
textBox2.Text = "No data found.";
}
reader.Close();
}
```
请将 YOUR_SERVER_NAME、YOUR_DATABASE_NAME、YOUR_TABLE_NAME、YOUR_COLUMN_NAME 和 YOUR_RESULT_COLUMN_NAME 替换为你自己的数据库连接信息和查询条件。注意,上面的代码只输出了查询结果的第一行数据,如果需要输出多行数据,可以在 while 循环中添加类似的代码。