views:

634

answers:

1

I'm using DataGridView in a WinForm app to show a table of data. Everything works fine except for the Caption Property of the DataColumn. I tried to set the Caption property but seems that DataGridView is using the Name of the DataColumn as the caption instead of the value of the Caption property ?

Have google for this and seems that this caption property is deliberately disabled.

My WinForm app is a localized one and I need to show caption in Chinese. Anyone know how can I do that?

Here is my code for setting up the data table

// Create a new DataTable.
DataTable table = new DataTable("Payments");

// Declare variables for DataColumn and DataRow objects.
DataColumn column;
DataRow row;

// Create new DataColumn, set DataType, 
// ColumnName and add to DataTable.    
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
column.Caption = LocalizedCaption.get("id") //LocalizedCaption is my library to retrieve the chinese caption

// Add the Column to the DataColumnCollection.
table.Columns.Add(column);


// Create three new DataRow objects and add them to the DataTable
for (int i = 0; i <= 2; i++)
{
    row = table.NewRow();
    row["id"] = i;
    table.Rows.Add(row);
}

//assign the DataTable as the datasource for a DataGridView
dataGridView1.DataSource = table;
+1  A: 

You have a few options. Here's a quick fix that should work, just add this at the end of your block of code:

        //Copy column captions into DataGridView
        for (int i = 0; i < table.Columns.Count; i++) {
            if (dataGridView1.Columns.Count >= i) {
                dataGridView1.Columns[i].HeaderText = table.Columns[i].Caption;
            }
        }

As you can see, this just copies over your existing column captions into the correct HeaderText property of each DataGridView column. This assumes that no previous columns exist in the DataGridView before you bind the DataTable.

Robert Venables