2011-10-18 48 views
1

我想根据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 

回答

3

好像你只需要计算在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 
+0

美丽,生病尝试 – user765942

+1

这可能会实现,但前提是字体是成比例的。 – TheBlastOne

+0

这是我的代码:Dim length = 0 For Each item As String In markCode.Items length = Max(length,item.Length)Next如果length> 0那么markCode.Width = length * CType(Me.markCode.Font.SizeInPoints ,整数)markCode.SelectedValue = markCode.SelectedText End If这里接收到的错误是'selectedValue不是systems.windows.forms.dataGridViewComboBoxColum的成员'任何想法? – user765942

0
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 
+0

你为什么从2岁以上的东西回答一些问题(没有解释答案)? –

+0

对不起,我遇到了同样的问题,上面的流行答案对我来说并没有100%的工作,所以我不得不以不同的方式做这件事,这是我的解决方案。我知道这是旧的,但这应该工作,并考虑到字体大小。 – muskrat