Reputation: 1424
I have a blank DataGridView, with no rows or datasource set, I need to populate it using a select query (and hide some of the returned columns).
I have tried 3 different code methods, all of which don't error, they just do nothing. I can query the database and populate lists fine using the below connection string.
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;
}
Upvotes: 0
Views: 3962