在 C# 中,如何像在 Excel 中一样在 DataGrid AutoFit Column Width 中制作列?目前我的五列是固定宽度,但列标题可以改变,所以我希望列自动适应列的宽度。
谢谢
DataGridView 上有一个名为 AutoSizeColumnsMode 的属性,它是一个枚举。可用的值为:
所有细胞
AllCellsExceptHeader
列标题
显示单元格
DisplayedCellsExceptHeader
充满
没有任何
让 BFree 的回答更进一步:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.autoresizecolumns.aspx
public static DataGrid AddDataGrid(DataGrid DG, object Me, System.Data.DataTable DS)
{
try {
DG.DataSource = DS;
Me.Controls.Add(DG);
DataGridTableStyle TblS = new DataGridTableStyle { MappingName = DS.TableName };
DG.TableStyles.Clear();
DG.TableStyles.Add(TblS);
for (ColIndex = 0; ColIndex <= DS.Columns.Count - 1; ColIndex++) {
int maxlength = 0;
Graphics g = DG.CreateGraphics();
// Take width of one blank space and add to the new width of the Column.
int offset = Convert.ToInt32(Math.Ceiling(g.MeasureString(" ", DG.Font).Width));
int i = 0;
int intaux = 0;
string straux = null;
int tot = DS.Rows.Count;
for (i = 0; i <= (tot - 1); i++) {
straux = DS.Rows[i][ColIndex].ToString();
// Get the width of Current Field String according to the Font.
intaux = Convert.ToInt32(Math.Ceiling(g.MeasureString(straux, DG.Font).Width));
if ((intaux > maxlength)) {
maxlength = intaux;
}
}
// Assign New Width to DataGrid column.
DG.TableStyles(DS.TableName).GridColumnStyles(ColIndex).Width = maxlength + offset;
}
} catch (Exception ex) {
Debug.WriteLine(ex.Message);
} finally {
DG.Show();
}
return DG;
}
使用此功能的示例...
private void AddDataGrid(DataSet Ds)
{
AddDataGrid(new DataGrid { Dock = DockStyle.Fill }, this, Ds.Tables[0]);
}
VB 这是我在表单上添加所有适合列的 DataGrid 的功能
Shared Function AddDataGrid(ByVal DG As DataGrid, ByVal This As Object, ByVal DS As System.Data.DataTable) As DataGrid
Try
DG.DataSource = DS
This.Controls.Add(DG)
Dim TblS As New DataGridTableStyle() With {.MappingName = DS.TableName}
DG.TableStyles.Clear()
DG.TableStyles.Add(TblS)
For ColIndex = 0 To DS.Columns.Count - 1
Dim maxlength As Integer = 0
Dim g As Graphics = DG.CreateGraphics()
' Take width of one blank space and add to the new width of the Column.
Dim offset As Integer = Convert.ToInt32(Math.Ceiling(g.MeasureString(" ", DG.Font).Width))
Dim i As Integer = 0
Dim intaux As Integer
Dim straux As String
Dim tot As Integer = DS.Rows.Count
For i = 0 To (tot - 1)
straux = DS.Rows(i)(ColIndex).ToString()
' Get the width of Current Field String according to the Font.
intaux = Convert.ToInt32(Math.Ceiling(g.MeasureString(straux, DG.Font).Width))
If (intaux > maxlength) Then
maxlength = intaux
End If
Next
' Assign New Width to DataGrid column.
DG.TableStyles(DS.TableName).GridColumnStyles(ColIndex).Width = maxlength + offset
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
Finally
DG.Show()
End Try
Return DG
End Function
使用此功能的示例...
Private Sub AddDataGrid(ByVal Ds As DataSet)
AddDataGrid(New DataGrid With {.Dock = DockStyle.Fill}, Me, Ds.Tables(0))
End Sub