我想从一个表(包含3行)中读取所有数据,并将所有数据添加到通用collection.Wana绑定(bind)到gridview。

下面显示的代码有效,但在网格 View 中仅最后一行显示了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; }
    }

输出是这样的:

最佳答案

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

同样,当同时使用数据读取器或直接打开连接时也不是一个好习惯
您应该使用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

关于c# - 从SQL数据库表读取数据到通用集合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15737425/

10-12 00:39
查看更多