2024/05/31(Fri) 04:20:51 編集(投稿者)
■No103154 (かんぼ さん) に返信
なるほど、こういう状態ですね。
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With DataGridView1
Const fiveLinesValue = "1" & vbCrLf & "2" & vbCrLf & "3" & vbCrLf & "4" & vbCrLf & "5"
Dim fiveLinesHeight As Integer
Using g = .CreateGraphics()
fiveLinesHeight = TextRenderer.MeasureText(g, fiveLinesValue, .Font).Height + 5
End Using
Dim cs = DataGridView1.ClientSize
.ClientSize = New Size(cs.Width, fiveLinesHeight + .ColumnHeadersHeight)
.Columns.Add(New DataGridViewTextBoxColumn With {.HeaderText = "Column1"})
Dim columnValue = "A1" & vbCrLf & "A2" & vbCrLf & "A3" & vbCrLf & "A4" &
vbCrLf & "A5" & vbCrLf & "A6" & vbCrLf & "A7"
.Rows.Add(columnValue)
.Rows.Add(columnValue.Replace("A", "B"))
.DefaultCellStyle.WrapMode = DataGridViewTriState.True
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
End With
End Sub
行の高さがクライアント領域をはみ出すから問題なので、はみ出さないよう調整すればよいと思います。
Private Sub AdjustRowHeight(dgv As DataGridView)
With dgv
.DefaultCellStyle.WrapMode = DataGridViewTriState.True
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
Dim maxRowHeight = .ClientSize.Height - .ColumnHeadersHeight - 1
Dim rowHeights = .Rows.Cast(Of DataGridViewRow).Select(Function(r) r.Height).ToArray()
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None
For i = 0 To rowHeights.Length - 1
If rowHeights(i) > maxRowHeight Then
.Rows(i).Height = maxRowHeight
Else
.Rows(i).Height = rowHeights(i)
End If
Next
End With
End Sub
そうすれば、編集状態にしたときのスクロールバーが生きます。
中身を編集したくないのであれば、ReadOnly にします。
Private Sub DataGridView1_EditingControlShowing(
sender As Object, e As DataGridViewEditingControlShowingEventArgs) _
Handles DataGridView1.EditingControlShowing
Dim editingControl = TryCast(e.Control, DataGridViewTextBoxEditingControl)
If editingControl IsNot Nothing Then
editingControl.ReadOnly = True
If editingControl.Multiline Then
editingControl.ScrollBars = ScrollBars.Vertical
Else
editingControl.ScrollBars = ScrollBars.None
End If
End If
End Sub