2011-10-18 11 views
1

ComboBoxの最長文字列の長さに基づいて、DataGridViewComboBoxColumnの長さを書式設定しようとしています。ここに私が現在持っているコードはありますが、コンボボックスの前の選択に基づいてDataGridViewComboBoxColumnの書式を設定するだけです。文字列の長さに基づくComboBoxの書式設定

DataGridViewComboBoxColumnをcomboBoxの最長文字列の長さにする方法はありますか?あなただけ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

それはそうです:

は、ここに私のコードです。値が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 String in markCode.Items length = Max(length、item.Length)Next length> 0 then markCode.Width = length * CType(Me.markCode.Font.SizeInPoints 、Integer)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

関連する問題