2016-03-21 13 views
0

空のDataGridViewがあり、行またはデータソースが設定されていません。selectクエリを使用してデータを設定し、返された列を非表示にする必要があります。SQLクエリを使用してDataGridViewにデータを入力します。

私は3つの異なるコード方法を試しましたが、どれもエラーはなく、何もしません。私は、データベースを照会し、下の接続文字列を使って細かいリストを作成することができます。

String connectionString = 
      "Data Source="  + Properties.Settings.Default.Sever + ";" + 
      "Initial Catalog=" + Properties.Settings.Default.Database + ";" + 
      "Integrated Security=TRUE;"; 

1)

public void populateDataGrid1() 
     { 
      SqlConnection cnn = new SqlConnection(connectionString); 

      SqlCommand sqlCmd = new SqlCommand(); 
      sqlCmd.Connection = cnn; 
      sqlCmd.CommandType = CommandType.Text; 
      sqlCmd.CommandText = "SELECT 1,2,3,4 from X inner join Y where Z"; 
      SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd); 

      DataTable dtRecord = new DataTable(); 
      sqlDataAdap.Fill(dtRecord); 
      dg_Data1.DataSource = dtRecord; 
     } 

2)

public void populateDataGrid2() 
     { 
      string select = "SELECT 1,2,3,4 from X inner join Y where Z"; 
      SqlConnection cnn = new SqlConnection(); 
      cnn.ConnectionString = connectionString; 
      SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cnn); 

      SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); 
      DataSet ds = new DataSet(); 
      dataAdapter.Fill(ds); 
      dg_Data1.ReadOnly = true; 
      dg_Data1.DataSource = ds; 
     } 

3)

string sql = "SELECT 1,2,3,4 from X inner join Y where Z"; 


      using (var connection = new SqlConnection(connectionString)) 
      using (var command = new SqlCommand(sql, connection)) 
      using (var adapter = new SqlDataAdapter(command)) 
      { 
       connection.Open(); 
       var myTable = new DataTable(); 
       adapter.Fill(myTable); 
       dg_Data1.DataSource = myTable; 

      } 
+0

DataGridViewのAutoGenerateColumnsプロパティを確認しましたか?それがどこかでfalseに設定されていると、新しい列は自動的に追加されません。また、クエリで何かが返されることを確認しましたか? – Tombala

+0

@Tombalaああ、これは修正されています、そのプロパティは、グリッドのプロパティリストに表示されていませんが、Loadでコードで手動で設定しました、ありがとう! – Vereonix

答えて

2

あなたはAutoGenerateColumns = trueを設定する必要があります。

関連する問題