J Talati J Talati - 1 year ago 51
Vb.net Question

Code to dynamically add number of comboboxes depending on the number of columns in a gridview

I basically wanted to know how we can code to add number of drop down list items depending on the number of column counts in a windows forms application in vb.net.

What I have tried:

Basically i know that you can get a count of all columns in a gridview by using this

GridView1.Rows(0).Cells.Count


However, i want to know lets say if the columns in the grid view when i run that gridview.rows(0).cells.count call comes out as 15.

I want to use that number 15 and dynamically add 15 drop down objects which will contain three list items: "test1", "test2", and "test3" on page load.

If you require more detail let me know and i will be replying right away.

Thank you and please provide a code and not just a theoretical answer please.

Answer Source

This should get you started.Loop and create comboboxes,add items and then add to the control collection.

If Not IsPostback Then
  For i As Integer = 0 To GridView1.Rows(0).Cells.Count - 1
    Dim cb As New ComboBox()

    cb.Id = "cb" + i.ToString() //Give unique id

    Dim item1 As New ComboBoxItem("test1", "test1")
    Dim item2 As New ComboBoxItem("test2", "test2")
    Dim item3 As New ComboBoxItem("test3", "test3")

    cb.Items.Add(item1)
    cb.Items.Add(item2)
    cb.Items.Add(item3)

    Me.Controls.Add(cb)
  Next
End If
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download