我正在尝试根据comboBox中最长字符串的长度来格式化DataGridViewComboBoxColumn的长度。这是我目前的代码,但它只根据用户以前在comboBox中的选择格式化DataGridViewComboBoxColumn。
有没有办法让DataGridViewComboBoxColumn占用comboBox中最长字符串的长度?
这是我的代码:
Private Sub comboTest_SelectionChangeCommitted(ByVal sender As Object, ByVal e As EventArgs) Handles comboTest.SelectionChangeCommitted
Dim senderComboBox As ComboBox = CType(sender, ComboBox)
'Change the length of the text box depending on what the user has
'selected and committed using the SelectionLength property.
If (comboTest.SelectionLength > 0) Then
comboTest.Width = comboTest.SelectionLength * CType(Me.comboTest.Font.SizeInPoints, Integer)
comboTest.SelectedValue = comboTest.SelectedText
End If
End Sub
答案 0 :(得分:4)
您似乎只需要计算ComboBox
中最长的字符串。假设它只是显示String
值的集合,您可以执行以下操作。
Dim length = 0
For Each item As String in comboTest.Items
length = Max(length, item.Length)
Next
If length > 0 Then
comboTest.Width = length * CType(Me.comboTest.Font.SizeInPoints, Integer)
comboTest.SelectedValue = comboTest.SelectedText
End If
答案 1 :(得分:1)
Dim length = 0
Dim maxlength = 0
Dim i As Integer = 0
Dim g As Graphics = ComboBox2.CreateGraphics
Dim stringsize As New SizeF
For i = 0 To ComboBox2.Items.Count - 1
ComboBox2.SelectedIndex = i
stringsize = g.MeasureString((ComboBox2.GetItemText(ComboBox2.Items(i))), ComboBox2.Font)
length = stringsize.Width
If length > maxlength Then
maxlength = length
End If
Next i
Me.ComboBox2.Width = maxlength