10

我想从表中读取所有数据(包含 3 行)并将所有数据添加到通用集合中。我想从集合中绑定到 gridview。

下面显示的代码有效,但只有最后一行在 gridview 中显示 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; }
    }

输出是这样的:

在此处输入图像描述

4

2 回答 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
于 2013-04-01T04:11:19.813 回答
3

在 DataReader while 循环中,为数据库表中的每一行实例化一个新 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);
}
于 2013-04-01T04:02:10.340 回答