The following code shows how to dynamically insert columns into DataGridView based on the data stored in a database. Since the datagridview can be crowded, it is required to make some column headings vertical. To do this, we need to enable resizing of the column header height and do the transformation in the event handler CellPainting.
Code: private void Form1_Load(object sender, EventArgs e)
{
string strSql = "<your SELECT statement>";
//get the column headings
ArrayList columnHeadings = ...
if (columnHeadings.Count > 0)
{
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
dataGridView1.ColumnHeadersHeight = 100;
}
else
{
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
}
for (int i = 0; i < columnHeadings.Count; i++)
{
DataGridViewColumn column = new DataGridViewCheckBoxColumn();
dataGridView1.Columns.Insert(dataGridViewCheckBoxColumn1.Index + 1, column);
column.HeaderText = columnHeadings[i].ToString();
column.Width = 20;
}
}
Code: private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1 && (e.ColumnIndex > dataGridViewCheckBoxColumn1.Index) && (e.ColumnIndex < dataGridViewCheckBoxColumn2.Index))
{
e.PaintBackground(e.CellBounds, true);
e.Graphics.TranslateTransform(e.CellBounds.Left, e.CellBounds.Bottom);
e.Graphics.RotateTransform(270);
e.Graphics.DrawString(e.FormattedValue.ToString(), e.CellStyle.Font, Brushes.Black, 5, 5);
e.Graphics.ResetTransform();
e.Handled = true;
}
}