We help IT Professionals succeed at work.

VB.net programatically add event to ComboBox

Murray Brown
Murray Brown used Ask the Experts™
Hi. I programatically add ComboBox columns to a DataGridView using the code below.
What additional code would I use to handle a selection being made manually from the ComboBox. I want to resize the column to fit the width of the selected text.

    Sub LoadDataGridViewColumns()

        Dim ColumnLetters As String
        Dim Ltr As Object
        Dim Target As Object
        Dim sColumnName As String
        Dim sColumnHeading As String

        Dim I As Integer
        For I = 1 To 100

            Ltr = Split(Globals.ThisAddIn.Application.Range(Globals.ThisAddIn.Application.Cells(1, I), Globals.ThisAddIn.Application.Cells(1, I)).Address(True, False), "$")
            ColumnLetters = Ltr(0)

            Target = Globals.ThisAddIn.Application.Range(Globals.ThisAddIn.Application.Cells(1, I), Globals.ThisAddIn.Application.Cells(1, I))

            'cboTemp.Name = ColumnLetters
            sColumnName = ColumnLetters
            sColumnHeading = ColumnLetters

            Dim xx As New DataGridViewComboBoxColumn

            xx.Name = sColumnHeading

            xx.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox

            xx.HeaderText = sColumnHeading


            Dim x2 As New DataGridViewTextBoxColumn

            x2.Name = sColumnHeading

            x2.HeaderText = sColumnHeading


        Next I
    End Sub
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

handle the cellvaluechanged event ofthe datagridview, filter for the combobox column and resize column,e.g
If sender.CurrentCell.ColumnIndex = 0 Then
 'here resize the column as desired
End If

Open in new window

Murray BrownASP.net/VBA/VSTO Developer


Hi. Thanks. How do I resize the column to fit the text without using the Autosize
Murray BrownASP.net/VBA/VSTO Developer


also sender.columnindex doesn't work
Ahh1, you need to typecast the sender to the (control) aka datatgridview (I ususally change my Objects to the respective controls!), and to set the size without using the autosizecolumnsmode, set the width, e.g
If CType(sender, DataGridView).CurrentCell.ColumnIndex = 0 Then
    CType(sender, DataGridView).Columns(0).Width = 20
End If

Open in new window

Murray BrownASP.net/VBA/VSTO Developer


Thanks very much