2013-04-01 86 views
10

我想從表中讀取所有數據(包含3行)並將所有數據添加到泛型集合中。從集合我wana綁定到gridview。從SQL數據庫表讀取數據到泛型集合

下面的作品,但只有最後一行顯示的代碼顯示3次gridview.Can你幫me.Am一個beginer

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

輸出是這樣的:

enter image description here

回答

15

您需要實例裏面你的對象,而循環
否則,你將有收集相同的數據
因此,代碼應該是

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 
2

在DataReader while循環中爲數據庫表中的每一行實例化新學生:

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