2016-06-11 100 views
0

我有以下代码来显示表中的DataGridView中的数据。但DataGridView是空的:DataGridView不显示数据

namespace WindowsFormsApplication5 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      MessageBox.Show("sdgds"); 
      SqlCommand sCommand; 
      SqlDataAdapter sAdapter; 
      SqlCommandBuilder sBuilder; 
      DataSet sDs; 
      DataTable sTable; 
      string sql = "SELECT * FROM mytable"; 
      SqlConnection myConnection = new SqlConnection("user id=test;" + 
             "password=test;server=MOBILE01;" + 
             "Trusted_Connection=yes;" + 
             "database=mydatabase; " + 
             "connection timeout=30"); 
      myConnection.Open(); 


      sCommand = new SqlCommand(sql, myConnection); 
      sAdapter = new SqlDataAdapter(sCommand); 
      sBuilder = new SqlCommandBuilder(sAdapter); 
      sDs = new DataSet(); 

      sAdapter.Fill(sDs); 


      sAdapter.Fill(sDs, "mytable"); 
      dataGridView1.ReadOnly = true; 

      dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
      myConnection.Close(); 
     } 
    } 
} 

回答

0

您还没有assinged的DataSourcegridview

dataGridView1.DataSource = sDs.Tabes[0]; 
-1

如果你的目标仅仅是要填充DataGridView以显示数据,那么您可能应该删除Dataset,DataAdapter填充例程:

private void Form1_Load(object sender, EventArgs e) 
     { 
      MessageBox.Show("sdgds"); 
      SqlCommand sCommand; 
      SqlCommandBuilder sBuilder; 
      DataTable sTable; 
      string sql = "SELECT * FROM mytable"; 
      SqlConnection myConnection = new SqlConnection("user id=test;" + 
             "password=test;server=MOBILE01;" + 
             "Trusted_Connection=yes;" + 
             "database=mydatabase; " + 
             "connection timeout=30"); 
      myConnection.Open(); 


      sCommand = new SqlCommand(sql, myConnection); 

      /// here is the change - getting data in data reader and filling datatable directly with it. 
      var reader = sCommand.ExecuteReader(); 
      sTable = new DataTable(); 
      sTable.Load(reader); 

      dataGridView1.DataSource = sTable; 
      dataGridView1.ReadOnly = true; 

      dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
      myConnection.Close(); 
     } 
    } 
+0

@techno为什么会在表单加载时显示消息?需要吗? –

+0

答案有什么问题?在这里提供一些学习曲线! –

+0

我没有downvote ... – techno