DataGrid - best way to configure column names?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi folks,

I am using the DataGrid control. I have linked it to a data source and am
currently reading in some data. However, the names of the columns are taking
on the names of the columns from the database i.e. job_number, job_title,
job_address etc... I would like to name the columns myself i.e. Job Number,
Job Title, Job Address etc...

How is this achievable??

Thanks for any help,

Best Regards,
David
 
Firstly, if you're using or would like to use .NET 2.0, I would highly
suggest you use the DataGridView control. You'll save yourself a lot
of headaches if you stay far, far away from the DataGrid control.

If that's not an option, though, you'll have to create a new
DataGridTableStyle. For every column, even the ones that you don't
want to rename the headers for, you must create a
DataGridTextBoxColumn, set up your desired style elements, and then add
that column to the DataGridTableStyle's GridColumnStyles collection.
Finally, you add that DataGridTableStyle you created to your DataGrid's
TableStyles collection.

Thusly:

private FormatGrid()
//dg is our datagrid
//colWidthOffset = 4

Graphics g = Graphics.FromHwnd(dg.Handle);

//customize columns
DataGridTableStyle ts = new DataGridTableStyle();
ts.MappingName = "DataBindingNameGoesHere";

DataGridTextBoxColumn station = new DataGridTextBoxColumn();
station.MappingName = DataLayer.eOrderDataCols.station.ToString();
station.HeaderText = "Station";
station.Alignment = HorizontalAlignment.Center;
station.Width =
Convert.ToInt32(Math.Ceiling(g.MeasureString(station.HeaderText.ToString(),
dg.Font).Width) + colWidthOffset);
station.ReadOnly = true;

ts.GridColumnStyles.Add(station);

dg.TableStyles.Add(ts);
}

This will show a grid with one column with "Station" in its header,
even though the name of the column in the bound object is "station".

If you want more columns, you've got to create more
DataGridTextBoxColumns and add them to the ts.GridColumnStyles
collection. You don't absolutely have to set all those properties I
did, but they help.

---Andy
 
Thanks Andy,

That helped a lot! Like you suspected I am unable to use the DataGridView
for my application (afaik)...it is for a mobile app. One potential limitation
I think the DataGrid may have is the lack tick box support for a column? i.e.
instead of displaying yes/no or true/false I would like a check box with a
tick, dont think this is possible with the data grid ;-(

Cheers,
David
 
Back
Top