Sunday, December 16, 2007

ComboBox in a DataGridView

It is often useful to add a dropdown box in a DataGridView column. I will list a couple of methods that can be used to achieve this. Of course, your real world applications will differ in certain areas related to the source of data. For the sake of this example, I have created these datasources at runtime.
The first example deals with displaying a two column grid with the first column containing the Employee Name and the second column that can be used to collect the Employee Gender
  1. Drag a DataGridView on the form

  2. Expand the DataGridView tasks and add a couple of columns


  3. Set the DataPropertyName for the first column appropriately, Since my data source deals with Employee Names, I have selected 'Name' which corresponds to the column name in my datasource.


  4. Finally, bind the data source with the grid and another datasource with the second column so that the dropdown choices are rendered correctly.

        'Create the sample list of names

        Dim dtNames As DataTable = New DataTable

        dtNames.Columns.Add("Name", GetType(String))

     

        Dim dr As DataRow

        dr = dtNames.NewRow : dr.Item("Name") = "Alvin Menezes" : dtNames.Rows.Add(dr)

        dr = dtNames.NewRow : dr.Item("Name") = "Saikumar Chettiar" : dtNames.Rows.Add(dr)

        dr = dtNames.NewRow : dr.Item("Name") = "Sample Name 1" : dtNames.Rows.Add(dr)

        dr = dtNames.NewRow : dr.Item("Name") = "Sample Name 2" : dtNames.Rows.Add(dr)

     

        'Create the sample list of dropdown choices

        Dim dtGenders As DataTable = New DataTable

        dtGenders.Columns.Add("Gender", GetType(String))

        dtGenders.Columns.Add("GenderId", GetType(Integer))

     

        dr = dtGenders.NewRow : dr.Item("GenderId") = 1 : dr.Item("Gender") = "Male" : dtGenders.Rows.Add(dr)

        dr = dtGenders.NewRow : dr.Item("GenderId") = 2 : dr.Item("Gender") = "Female" : dtGenders.Rows.Add(dr)

     

        'Bind the datagridview

        dgvSample.AutoGenerateColumns = False

        dgvSample.DataSource = dtNames

     

        'Setup the Combobox column

        Dim dgvComboCol As DataGridViewComboBoxColumn = CType(dgvSample.Columns(1), DataGridViewComboBoxColumn)

        With dgvComboCol

          .DisplayMember = "Gender"

          .ValueMember = "GenderId"

          .DataSource = dtGenders

        End With



And that's it, we are good to go

No comments: