hi - i binded a datatable to a datagridview datasource. Now the problem is the columns in my datagridview cannot be customized. Does anyone know how to do this? It seems that the columns are dynamically created from the datasource. I need to custom to the font, color column names, etc... any thoughts?
A:
If you are doing this in C# (?) you can set the datagridview AutoGenerateColumns
property to false
and dynamically add them yourself. This will then allow you to customise them.
The datagridview column has a DataPropertyName
which you set to the name of the column in the datatable that you want it to display.
For example:
// Create new combo box column.
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
// Set properties.
column.DataPropertyName = colName;
column.Name = colName;
column.HeaderText = colName;
column.DropDownWidth = 160;
column.Width = 90;
column.MaxDropDownItems = 5;
column.FlatStyle = FlatStyle.Standard;
datagridview.Columns.Add(column);
You then just bind it to the datatable.
w69rdy
2010-07-07 15:18:08
after i set AutoGenerateColumns to false, how do i link the columns?
gd2
2010-07-07 15:22:44
If this answer is useful can you give it a vote or mark as the answer. Thanks
w69rdy
2010-07-07 16:08:55
Hi - thanks for the update. The part I dont understand is how to bind a column that is defined to a dynamic datatable. can you provide the code sample for binding? thanks greg
gd2
2010-07-07 22:02:28
You bind it by setting the DataPropertyName of the datagridview column to the name of the datatable column ie. So you will need to do it for all the columns you want to display.column.DataPropertyName = datatable.Columns[i].ColumnName; Read this for more info. http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.datapropertyname.aspx
w69rdy
2010-07-08 09:15:18
A:
You should be able to auto-generate the columns and still customize them.
For example, to change a column's font you could do:
dataGridView.Columns["ColumnName"].DefaultCellStyle.Font = new Font("Tahoma, 15);
To change the colour of the column name:
dataGridView.Columns["ColumnName"].HeaderCell.Style.BackColor = Color.Blue;
I've tried both of these in an auto-generated DataGridView bound to a DataTable and it works for me.
recoisiche
2010-07-27 00:58:26