DataGridView Column Headers

D

David Veeneman

How can I set a bound DataGridView control to use a dataset table's column
captions, instead of column names?

I'm working with a DataGridView control, which I have bound to a table in a
dataset. The dataset is created at run time, so I don't know column headers
in advance. The table's column captions are set at run time, using the
DataColumn.Caption property. The table is bound to the grid using the grid's
DataSource property. Here is my problem: The grid displays column names,
rather than captions, as it's header text.

Right now, I'm inserting the captions using a loop:

// Initialize Investments grid
gridInvestments.DataSource = myDataset.Tables["Investments"];
for (int i = 0; i < gridInvestments.ColumnCount; i++)
{
gridInvestments.Columns.HeaderText =
myDataset.Tables["Investments"].Columns.Caption;
}

I'm looking for a simpler way to get the job done.

Is there a DataGridView property that will tell the grid to get column
headers from the DataColumns' Caption property, rather than the Name
property? Thanks in advance
 
N

Nicholas Paldino [.NET/C# MVP]

David,

That's pretty much the way I would do it. Unfortunately, the binding
mechanism is pretty generic (using reflection and implemented interfaces to
get this information). This mechanism, however, does not have any way for
the data source to expose the column header information (after all, you can
bind to anything that implements IList).

What you have is fine.

If anything, you could derive a class from DataGridView which will do
this for you.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top