DataGrid - setting column width

本文详细介绍了在数据网格控件中,当字段名过长导致只显示部分内容时,如何通过编程调整宽度以确保完整显示字段名的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

<DataGrid x:Name="da" ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto" CanUserResizeRows="False" CanUserResizeColumns="False" FontSize="35" AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True" SelectionUnit="Cell"> <!--AutoGenerateColumns="False"时,不自动生成列,否则可以自动生成列名,列名和数据库列名一致 CanUserAddRows="False" 禁止用户添加行 IsReadOnly="True" 禁止修改 SelectionUnit="Cell" 选中方式:单元格,不设置默认选择整行() --> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="Height" Value="90" /> <Setter Property="FontSize" Value="35"/> </Style> </DataGrid.RowStyle> <!--<DataGrid.CellStyle> <Style TargetType="DataGridCell"> </Style> </DataGrid.CellStyle>--> <DataGrid.Resources> <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">30</sys:Double> <sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">30</sys:Double> </DataGrid.Resources> <!--表头样式--> <DataGrid.ColumnHeaderStyle> <Style TargetType="DataGridColumnHeader"> <Setter Property="HorizontalContentAlignment" Value="Center"></Setter> <Setter Property="Background" Value="Transparent"></Setter> <Setter Property="Foreground" Value="black"></Setter> <Setter Property="BorderThickness" Value="0.8" /> <Setter Property="BorderBrush" Value="#17acae" /> <Setter Property="FontSize" Value="40" /> <Setter Property="Height" Value="100" /> </Style> </DataGrid.ColumnHeaderStyle> <DataGrid.Columns> <DataGridTemplateColumn Header="序号" Width="0.7*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Converter={StaticResource RowToIndexConverter}}" HorizontalAlignment="Center" VerticalAlignment="Center"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTextColumn Header="报警时长" Binding="{Binding 报警时长}" Width="*"> <DataGridTextColumn.ElementStyle> <Style TargetType="TextBlock"> <Setter Property="HorizontalAlignment" Value="Center"/> <Setter Property="VerticalAlignment" Value="Center"/> </Style> </DataGridTextColumn.ElementStyle> </DataGridTextColumn> <!--<DataGridTextColumn Header="公差" Binding="{Binding 公差}" Width="*"> <DataGridTextColumn.ElementStyle> <Style TargetType="TextBlock"> <Setter Property="HorizontalAlignment" Value="Center"/> <Setter Property="VerticalAlignment" Value="Center"/> </Style> </DataGridTextColumn.ElementStyle> </DataGridTextColumn>--> <DataGridTemplateColumn Header="是否开启" Width="*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Grid> <Button x:Name="but1" Grid.Row ="0" Width="140" Height="70" HorizontalAlignment="Center" VerticalAlignment="Center" Click="But1_Click"> <Button.Template> <ControlTemplate TargetType="Button"> <Grid> <Border x:Name="border" Background="LightGray" BorderThickness="0" CornerRadius="35"></Border> <TextBlock Text="OFF" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0" FontSize="30"></TextBlock> <Ellipse x:Name="ellipse" Height="70" Width="70" Fill="White" HorizontalAlignment="Left"></Ellipse> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter TargetName="border" Property="Background" Value="Gray"></Setter> </Trigger> <Trigger Property="IsFocused" Value="true"> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Button.Template> </Button> <Button x:Name="but2" Grid.Row ="0" Width="140" Height="70" HorizontalAlignment="Center" VerticalAlignment="Center" Click="But2_Click" Visibility="Collapsed"> <Button.Template> <ControlTemplate TargetType="Button"> <Grid> <Border x:Name="border" Background="LightGreen" BorderThickness="0" CornerRadius="35"></Border> <TextBlock Text="ON" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,0,0,0" FontSize="30"></TextBlock> <Ellipse x:Name="ellipse" Height="70" Width="70" Fill="White" HorizontalAlignment="Right"></Ellipse> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter TargetName="border" Property="Background" Value="Green"></Setter> </Trigger> <Trigger Property="IsFocused" Value="true"> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Button.Template> </Button> </Grid> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="操作" Width="1.2*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition></ColumnDefinition> <ColumnDefinition></ColumnDefinition> </Grid.ColumnDefinitions> <Grid> <Button Height="60" Width="60" Margin="60,0,0,0" Click="Xg_Click"> <Button.Template> <ControlTemplate TargetType="Button"> <Grid> <Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="Gray" BorderThickness="5" CornerRadius="0"> <Rectangle> <Rectangle.Fill> <ImageBrush ImageSource="image/xg.png" Stretch="Fill"/> </Rectangle.Fill> </Rectangle> </Border> </Grid> </ControlTemplate> </Button.Template> </Button> </Grid> <Grid Grid.Column="1"> <Button Height="60" Width="60" Margin="0,0,60,0" Click="Sc_Click"> <Button.Template> <ControlTemplate TargetType="Button"> <Grid> <Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="Gray" BorderThickness="5" CornerRadius="0"> <Rectangle> <Rectangle.Fill> <ImageBrush ImageSource="image/sc.png" Stretch="Fill"/> </Rectangle.Fill> </Rectangle> </Border> </Grid> </ControlTemplate> </Button.Template> </Button> </Grid> </Grid> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> 这是DataGrid,我没有ID列啊,为什么能 string primaryKey = rowToDelete["ID"].ToString();获取到序号列?
最新发布
08-13
<div style=";text-align:center;;height:auto;" class="datagrid-cell datagrid-cell-c1-checkId">已通过</div></td><td field="button"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-button"><a href="#" style="color: red" onclick="fileManager(0)">图片管理</a></div></td><td field="truckNo"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-truckNo">辽PD6885</div></td><td field="truckCardColor"><div style=";text-align:center;;height:auto;" class="datagrid-cell datagrid-cell-c1-truckCardColor">黄牌</div></td><td field="vtNam"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-vtNam">秦皇岛九福物流有限公司</div></td><td field="driverNam"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-driverNam">叶红建</div></td><td field="linkTel"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-linkTel">13842929049</div></td><td field="workCompanyCod"><div style=";text-align:center;;height:auto;" class="datagrid-cell datagrid-cell-c1-workCompanyCod">金海粮油</div></td><td field="cargoNam" style="display:none;"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-cargoNam"></div></td><td field="consignCod" style="display:none;"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-consignCod"></div></td><td field="planDte"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-planDte">2023-05-01</div></td><td field="validTyp"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-validTyp">当天有效</div></td><td field="ifEnd"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-ifEnd">x</div></td><td field="individualId" style="display:none;"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-individualId">0</div></td><td field="rejectReason"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-rejectReason"></div></td><td field="checkNam"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-checkNam">jhly</div></td><td field="checkTim"><div style=";height:auto;" class="datagrid-cell datagrid-cell-c1-checkTim">2023-04-29 21:09</div></td>以上代码为网页源码,帮我写一段python程序从以上代码中找出drivernam和checkTim并保存数据库中
06-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值