c# – 将数据从SQL DataBase表读取到通用集合

我想从表中读取所有数据(包含3行),并将所有数据添加到通用集合中.从集合我wana绑定到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; }
    }

输出如下:

解决方法

你需要在循环中实例化你的对象
否则,您将收集相同的数据
所以代码应该是
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();
}

此外,使用数据读取器或直接打开连接不是一个好习惯
你应该使用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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...