I have a datagrid control on a form. The form takes as input a query to a sql server database, and properly returns the rows associated with the query into the datagrid. I have used
dataGrid1.Columns.StretchToFit()
in my code to force the column width to fit the contents. This works fine, but in some cases, the field name is longer than the data width, so that only a portion of the field name is shown as a column header. For example, I have a table with a list of storm identifiers (in a column name StormIdentifier) and an associated values of H-1, H-2, H-3, etc.. The returned datagrid display shows "Sto..." as the column name, when I would like it to be StormIdentifier, which is the field name in the table. There is no problem if the column content is larger than the column name, it then gets set to display correctly, but not for the case where the column name is longer than the contents. Is there any way of insuring that the larger width will govern the display (column name or column contents)?
Thank you in advance.
Richard Males
Cincinnati, OH
I got no reply to my previous post, so I resolved the issue, rather inelegantly, as shown below. I would appreciate it if somebody could tell me how to better translate the width of the header column (known in characters) into the required number of pixels to set the column width. I explored issues of font size, but did not immediately find anything that returns number of pixels needed for a given string. Any help would be greatly appreciated.
dataGrid1.Rows.StretchToFit();
dataGrid1.Columns.StretchToFit();
dataGrid1.AutoSizeCells();
// adjust column widths
int columnWidth;
string columnHeader;
int columnHeaderLength;
for (int k = 1; k < dataGrid1.Columns.Count; k++)
{
columnHeader = dataGrid1.Columns[k].PropertyName;
columnHeaderLength = columnHeader.Length;
columnWidth = dataGrid1.Columns[k].Width;
// assume 6 pixels per character
if (columnWidth<(6*columnHeaderLength))
dataGrid1.Columns[k].Width = 6 * columnHeaderLength + 20;
}
Richard Males
Cincinnati, OH