简体   繁体   中英

Dynamically ADD Columns to dataGridView

Lets say I have over 300 cols in my database table, as each col after col # 3 are the same data type, Is there an efficient way to load the cols from the SqlCeConnection/SqlCeDatabase ?

private void loadDataGridView() {
  String CmdString = "...... FROM MyDatabaseTable"; //some sql to get col info
  SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
  SqlCeDataAdapter sda = new SqlCeDataAdapter(cmd);
  DataTable dt = new DataTable("mastertable");
  sda.Fill(dt);
  foreach(Col col in dt) {
    DataGridViewColumn c = new DataGridViewColumn(..); //Create the Col
    c.DataPropertyName = col.Name; //Bind the col and property name
    dataGridView1.Cols.Add(new dataGridViewColumn(...) ); //Add the col
  }
}

I found online that the DataGridView has this facility by setting a single property.

dataGridView1.AutoGenerateColumns = true; //as long as the Data is defined in DB it works perfectly.

This was found here

http://www.codeproject.com/Questions/182662/c-net-fill-data-to-already-defined-columns-in-data

Hope this helps you guys too :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM