如果 studentID 是表的主键,则使用:
DataRow row = dt.Rows.Find(studentID);
if (row != null)
textBox1.Text = row["StudentName"].ToString();
否则使用dt.Select
方法。顺便说一句,将数据访问代码与 UI 代码混合并不是一个好主意
更新:你也可以使用 LINQ
string name = (from row in dt.AsEnumerable()
where row.Field<int>("StudentID") == studentID
select row.Field<string>("StudenName"))
.Single();
更新:如果您正在输入学生 id 并想要获取学生姓名,那么您可以从数据库中检索学生姓名,将参数传递给 sql 命令:
private string GetStudentName(int studentID)
{
string connString = @"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connString))
{
string query = "SELECT StudentName FROM Entry WHERE StudentID = @studentID";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("@studentID", SqlDbType.Int).Value = studentID;
conn.Open();
return (string)cmd.ExecuteScalar();
}
}
还考虑只返回第一个条目(如果 StudentID 不是 PK)并验证 DbNull。
更新:如果您需要检索学生的多个属性,那么我创建了学生类:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Grade { get; set; }
}
并从数据阅读器中填充其属性:
private Student GetStudent(int studentID)
{
string connString = @"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connString))
{
string query = "SELECT * FROM Entry WHERE StudentID = @studentID";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("@studentID", SqlDbType.Int).Value = studentID;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (!reader.Read())
throw new Exception("Student not found");
return new Student()
{
Id = (int)reader["StudentID"],
Name = (string)reader["StudentName"],
Grade = (string)reader["Grade"]
};
}
}
然后,当您在文本框中输入学生 ID 时,从数据库中检索学生并在控件中显示其属性:
int studentID = Int32.Parse(idTextBox.Text);
Student student = GetStudent(studentID);
nameTextBox.Text = student.Name;
gradeTextBox.Text = student.Grade;