2016-09-02 65 views
1

在我的數據庫中有一個名爲student的表。這個表有6行,但我的Windows窗體的datagridview顯示6個空行。我嘗試了幾種方法,包括studentdataGridView.AllowUserToAddRows = true/false;,但沒有任何工作。它顯示空行。datagridview在窗體中顯示空行

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Data.SqlClient; 

namespace varsityProject 
{ 
    public partial class report : Form 
    { 
     public report() 
     { 
      InitializeComponent(); 
     } 

     private void report_Load(object sender, EventArgs e) 
     { 
      string connectionString = @"Server=.\SQLEXPRESS; Database = varsityproject; integrated Security = true"; 
      SqlConnection connection = new SqlConnection(connectionString); 
      string query = "SELECT * FROM student"; 
      SqlCommand command = new SqlCommand(query, connection); 
      connection.Open(); 

      SqlDataReader reader = command.ExecuteReader(); 

      List<students> stu = new List<students>(); 
      students student2 = new students(); 

      while (reader.Read()) 
      { 
       student2.id = (int)reader["id"]; 
       student2.firstname = reader["firstname"].ToString(); 
       student2.lastname = reader["lastname"].ToString(); 
       student2.program = reader["program"].ToString(); 
       student2.birthdate = reader["birthdate"].ToString(); 
       student2.fathersname = reader["fathersname"].ToString(); 
       student2.mothersname = reader["mothersname"].ToString(); 
       student2.presentaddress = reader["presentaddress"].ToString(); 
       student2.permanentaddress = reader["permanentaddress"].ToString(); 
       stu.Add(student2); 
      } 
      reader.Close(); 
      connection.Close(); 
      studentdataGridView.DataSource = stu; 
     } 
    } 
} 
+3

* 1)*移動'學生STUDENT2 =新的學生() ;'進入循環。 * 2)*與我們分享'學生'的代碼。 * 3)*使用'SqlDataAdapter'加載數據更簡單,如果需要,可以將數據加工到'List '。 –

+0

您是否驗證過您可以連接到sql數據庫 –

+0

是的,mysql數據庫連接正常 – anasbiswas

回答

0

上面的代碼您發佈工作正常沒有任何問題。

您的學生的屬性(POCO)類應該是:

public class students 
{ 
    public int id { get; set; } 
    public string firstname { get; set; } 
    public string lastname { get; set; } 
    public string program { get; set; } 
    public string birthdate { get; set; } 
    public string fathersname { get; set; } 
    public string mothersname { get; set; } 
    public string presentaddress { get; set; } 
    public string permanentaddress { get; set; } 
} 

,你的表模式應該是:

enter image description here