C#根据从textbox1输入的ID数据从数据库中获取Name并出现在textbox2
时间: 2024-11-24 19:42:00 浏览: 22
在C#中,你可以通过以下步骤从数据库中获取用户输入的ID对应的Name,并显示在TextBox2中:
1. 首先,确保你已经连接到数据库并且使用了适当的ORM库(如Entity Framework、ADO.NET等)来进行交互。
```csharp
using System.Data.SqlClient; // 如果使用的是Sql数据库
// 创建SqlConnection对象,连接字符串应包含数据库信息
string connectionString = "your_connection_string_here";
SqlConnection connection = new SqlConnection(connectionString);
// 创建SqlCommand对象用于执行SQL查询
string idInput = textBox1.Text;
SqlCommand command = new SqlCommand($"SELECT Name FROM YourTable WHERE ID = @id", connection);
command.Parameters.AddWithValue("@id", idInput); // 参数化查询防止SQL注入
try {
// 打开数据库连接并执行查询
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// 如果查询结果存在,则读取第一条记录
if (reader.HasRows) {
reader.Read();
string name = reader["Name"].ToString(); // 获取Name字段的值
textBox2.Text = name; // 将Name显示在textBox2中
} else {
textBox2.Text = "未找到对应名称"; // 没有找到匹配的结果时的提示
}
// 关闭读取器和连接
reader.Close();
connection.Close();
}
catch (Exception ex) {
MessageBox.Show("错误:" + ex.Message);
}
finally {
// 确保关闭连接资源
if (connection.State == ConnectionState.Open)
connection.Close();
}
```
阅读全文
相关推荐


















