//
You're reading...
Controls, DatagridView

Populate DataGridViewComboBoxColumn at Runtime

This will demonstrate how you can bind DataGridViewComboBoxColumn to your DataGridView and populate it.

The way you can follow, is to create and add a DataGridViewComboBoxColumn in your datagridview and populate every combo Box with the values in an iterative manner.

Here I have discussed two approaches:

See the code, here Db2DataSet is filled before

Method#1:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   DataGridView1.DataSource = Db2DataSet.Tables(0)
   DataGridView1.Columns.Add(New DataGridViewComboBoxColumn() With {.HeaderText = "ComboColumn", .Name = "ComboColumn"})
   For i As Integer = 0 To Db2DataSet.Tables(0).Rows.Count - 1
      For j As Integer = 0 To Db2DataSet.Tables(0).Rows(i).ItemArray().Count - 1
            If j <> 1 Then
              DataGridView1.Rows(i).Cells(j).Value = Db2DataSet.Tables(0).Rows(i).Item(j)
            Else
              Dim c As DataGridViewComboBoxCell = New DataGridViewComboBoxCell()
              For Each rho As DataRow In Db2DataSet.Tables(0).Rows
                     c.Items.Add(rho.Item(1)) Next DataGridView1.Rows(i).Cells("ComboColumn") = c
              End If
       Next
    Next
End Sub

Method#2:  (Using Linq)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  DataGridView1.AutoGenerateColumns = False
  DataGridView1.DataSource = Db2DataSet.Tables(0)
  DataGridView1.Columns.Add(New DataGridViewComboBoxColumn() With {.HeaderText = "ComboColumn", .Name = "ComboColumn"})
  Dim Lst As New List(Of Object) Dim query = From d In Db2DataSet.Tables(0) _
                                                                           Select d.ItemArray.GetValue(1)
  Lst.AddRange(query.ToArray)
  DirectCast(DataGridView1.Columns("ComboColumn"), DataGridViewComboBoxColumn).DataSource = Lst
End Sub

:

Advertisements

About Shahan Ayyub

Shahan is a Microsoft Certified Professional of .Net. Mostly self taught programmer and a quick learner, who just love to code and always eager to find unique solutions to the common problems. Currently working as an iOS developer.

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: