0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【VB.NET】DataGridviewの列の幅を文字列の幅に合わせて調整する方法

Posted at

やりたいこと

  • DataGridviewの列の幅を、各列のセル内のテキストで一番長いテキストの幅に合わせる。
    やりたいこと.png

コード

''' <summary>
''' DataGridviewの幅を一番長い文字列の幅に合わせる処理
''' </summary>
''' <param name="columnIndex">列番号</param>
Public Sub autoSizeDGVColumnWidth(columnIndex As Integer)
	' DataGridViewのGraphicsを取得
	Dim gGrid As Graphics = Graphics.FromHwnd(DGVCard.Handle)

	' すべてのセルを調べて、一番広い幅を取得
	Dim sf As New StringFormat(StringFormat.GenericTypographic)
	Dim dt As DataTable = CType(DGVCard.DataSource, DataTable)      ' DGVにバインドしたデータをDataTable型に変換
	Dim rowsCount As Integer = dt.Rows.Count
	Dim maxWidth As Single = 0
	For i As Integer = 0 To rowsCount - 1
		Dim text As String = CStr(DGVCard.Rows(i).Cells(columnIndex).Value)     ' セルの内の値を文字列に変換
		' セル内の値の長さと現時点の最大幅を比較する
		maxWidth = Math.Max(gGrid.MeasureString(text, DGVCard.Font, DGVCard.Width, sf).Width, maxWidth)
	Next i

	' ヘッダー幅を調べる
	Dim dgv As DataGridViewCellStyle = DGVCard.ColumnHeadersDefaultCellStyle
	maxWidth = Math.Max(gGrid.MeasureString(DGVCard.Columns(columnIndex).HeaderText, dgv.Font, DGVCard.Width, sf).Width, maxWidth)

	' 破棄する
	gGrid.Dispose()

	' 幅の変更
	If DGVCard.Columns(columnIndex).HeaderText.Count > 10 Then
		DGVCard.Columns(columnIndex).Width = CInt(maxWidth)
	Else
		DGVCard.Columns(columnIndex).Width = CInt(maxWidth) + 50
	End If
End Sub
  • 幅の変更
    if文を追加しなかった場合、DataGridviewのヘッダー列が折り返して表示された。
    image 41.png

 ヘッダー列の文字数が10文字より多い場合は幅を50プラスして設定する処理を追加した。
  image 42.png


参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?