设计 假设有一张数据表student,根据表的字段编写Student类public class Student { public Student(){} public Student(string name,int age,string hobby) { this.Name = name; this.Age = age; this.Hobby = hobby; } public int ID{get;set;} public string Name{get;set;} public int Age{get;set;} public string Hobby{get;set;} } 编写数据访问层类,根据ID查询student信息public List<Student> GetStudentByID(int id) { List<Student> list = new List<Student>();
using(SqlConnection connection = new SqlConnection("数据库连接字符串")) { string sql = string.Format("select * from student where ID = @ID");
using(SqlCommand objCommand = new SqlCommand(sql,connection)) { connection.Open();
根据个人信息设置查询调件,在数据库中查询到后,赋给窗体中的变量,显示出来,就行了。
要用到SQL语言。
string connString = "Data Source=.;Initial Catalog=Sql;User ID=sa;Pwd=123";
// 创建 Connection 对象
SqlConnection connection = new SqlConnection(connString);
// 打开数据库连接
connection.Open();
string sqlString = "select * from Student";
SqlCommand comm = new SqlCommand(sqlString,connection);
SqlDataReader dr = comm.ExecuteReader();
if (dr.Read())
{
string ID = dr.GetString(dr.GetOrdinal("stuId"));
string Name = dr.GetString(dr.GetOrdinal("stuName"));
}
我想知道,要怎么把结果显示在窗体中呢?
...
就知道什么是动态了
不过我觉得你好像没有考虑到重点,难点应该在数据库方面,窗体显示是基本的,也很简单啊。
label.Text = dr.GetString(i);
根据ID从表里查询就可以了。
假设有一张数据表student,根据表的字段编写Student类public class Student
{
public Student(){}
public Student(string name,int age,string hobby)
{
this.Name = name;
this.Age = age;
this.Hobby = hobby;
}
public int ID{get;set;}
public string Name{get;set;}
public int Age{get;set;}
public string Hobby{get;set;}
}
编写数据访问层类,根据ID查询student信息public List<Student> GetStudentByID(int id)
{
List<Student> list = new List<Student>();
using(SqlConnection connection = new SqlConnection("数据库连接字符串"))
{
string sql = string.Format("select * from student where ID = @ID");
using(SqlCommand objCommand = new SqlCommand(sql,connection))
{
connection.Open();
using(SqlDataReader objReader = objCommand.ExecuteReader())
{
if(objReader.HasRows)
{
if(objReader.Read())
{
Student student = new Student(objReader["Name"].ToString(),Convert.ToInt32(objReader["Age"]),objReader["Hobby"].ToString()); list.Add(student);
}
}
}
}
} return list;
}
创建窗体,拖放一个DataGridView,设置三列,分别存储姓名,年龄,爱好,并且设置其DatapropertyName属性与表中字段一致。然后将数据访问层的返回的List集合赋值与DataGridViewthis.DataGridView1.DataSource = 数据层返回来的List集合;