从SQL数据库表中读取数据到通用集合

10

我想要从一个包含3行的表格中读取所有数据,并将所有数据添加到通用集合中。然后我想要从集合中绑定到网格视图。

下面显示的代码是有效的,但是在网格视图中仅显示最后一行3次。你能帮我吗?我是一个初学者。

protected void Page_Load(object sender, EventArgs e)
{
    List<Student> listid = new List<Student>();
    Student stud = new Student();
    SqlConnection con = new SqlConnection("........");
    string sql = "select * from StudentInfo";
    con.Open();
    SqlCommand cmd = new SqlCommand(sql, con);
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        stud.Studid = Convert.ToInt32(dr["StudId"]);
        stud.StudName = dr["StudName"].ToString();
        stud.StudentDept = dr["StudentDept"].ToString();
        listid.Add(stud);               
    }
    GridView1.DataSource = listid;
    GridView1.DataBind();
}
public class Student
{
    private int studid;
    public int Studid
    {
       get { return studid; }
       set { studid = value; }
    }    
    private string studName;
    public string StudName
    {
       get { return studName; }
       set { studName = value; }
    }
    private string studentDept;
    public string StudentDept
    {
       get { return studentDept; }
       set { studentDept = value; }
    }
输出如下:

在此输入图片描述

2个回答

20

您需要在 while 循环内实例化对象
否则,集合中将具有相同的数据
因此代码应该如下:

protected void Page_Load(object sender, EventArgs e)
{
    List<Student> listid = new List<Student>();
    SqlConnection con = new SqlConnection("........");
    string sql = "select * from StudentInfo";
    con.Open();
    SqlCommand cmd = new SqlCommand(sql, con);
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        Student stud = new Student();
        stud.Studid = Convert.ToInt32(dr["StudId"]);
        stud.StudName = dr["StudName"].ToString();
        stud.StudentDept = dr["StudentDept"].ToString();
        listid.Add(stud);               
    }
    GridView1.DataSource = listid;
    GridView1.DataBind();
}

同时,在数据读取器或直接打开连接时使用while循环不是一个好的实践方式。
你应该使用 using 语句。

using(SqlConnection con = new SqlConnection("connection string"))
{

    con.Open();

    using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            if (reader != null)
            {
                while (reader.Read())
                {
                    //do something
                }
            }
        } // reader closed and disposed up here

    } // command disposed here

} //connection closed and disposed here

3
在DataReader循环中,为数据库表中的每一行实例化一个新的Student对象:
while (dr.Read())
{
 var stud = new Student();
 stud.Studid = Convert.ToInt32(dr["StudId"]);
 stud.StudName = dr["StudName"].ToString();
 stud.StudentDept = dr["StudentDept"].ToString();
 listid.Add(stud);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接