日期:2014-05-18  浏览次数:20789 次

datagrid动态生成列的问题,请大家快来帮帮忙
我想通过数据库查询出来的结果来动态生成datagrid的列,比如我查询表A中的yewu字段,查出的结果有业务1,业务2,业务3三项。我想把业务1,业务2,业务3这三项作为datagrid的三列,而且作表头

------解决方案--------------------
C# code

      DataTable tbl = new DataTable();
      //从数据库得到数据。

       DataTable gridDataSource = new DataTable();
       foreach(DataRow row in tbl.Rows)
      {
        DataColumn col = new DataColumn((string) row["yewu"]);
        gridDataSource.Columns.Add(col);
      }

      DataGridView grid = new DataGridView();
      grid.DataSource = gridDataSource;

------解决方案--------------------
SqlCommand cmd = new SqlCommand("select yewu from table where id=1", cn);
SqlDataReader dr = cmd.ExecuteReader();

ArrayList list = new ArrayList();

while (dr.Read())
{
list.Add(dr.GetString(0));
}

dataGridView1.ColumnCount = list.Count;
for (int i = 0; i < list.Count;i++ )
{
dataGridView1.Columns[i].HeaderText = list[i].ToString();
}