2016-09-02 7 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

関連する問題