C# 从 SQL 数据库表读取数据到泛型集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15737425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:47:40  来源:igfitidea点击:

Reading Data from SQL DataBase Table to generic collection

c#

提问by user2115618

I wanted to read all data from a table(containg 3 rows) and to add all the data into generic collection.From collection i wana bind to gridview.

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

The code displayed below works but only last row is displayed 3 times in gridview.Can You help me.Am a beginer

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

The output is like this:

输出是这样的:

enter image description here

在此处输入图片说明

采纳答案by ????

You need to instantiate your object inside while loop
Otherwise you will have same data in the collection
So the code should be

您需要在 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();
}

Also it is not a good practice to use while to data reader or directly open connection
You should use usingstatement.

此外,使用 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

回答by Jeremy Thompson

In the DataReader while loop instantiate a new Student for each row in the database table:

在 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);
}