gd2
gd2

Reputation: 21

binding a datagridview datasource to a datatable

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?

Upvotes: 1

Views: 1846

Answers (3)

Tzu ng
Tzu ng

Reputation: 9234

Use annotation instead. Example :

internal class FailedItem
{
   ...
   [DisplayName("Clarify reason")]
   public string Reason
   { get; private set; }
   ...
}

Upvotes: 0

C Walker
C Walker

Reputation: 803

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.

Upvotes: 1

Iain Ward
Iain Ward

Reputation: 9936

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.

Upvotes: 3

Related Questions