DataGrid - setting column width

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值