2011-10-18 50 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