我有一个空白的DataGridView,没有设置行或数据源,我需要使用select查询填充它(并隐藏一些返回的列)。
我尝试了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 :(得分:2)
您需要设置AutoGenerateColumns = true。