vbnewbie vbnewbie - 1 year ago 76
SQL Question

How to create usercontrol dynamically?

i have a flowlayoutpanel in my winform,
i want to add some button into the flowlayoutpanel when the form is loaded,
the number of button will depend on how many item(row) exist in my dataset


Private Sub temp_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub

Private Sub FlowLayoutPanel1_Paint(sender As Object, e As PaintEventArgs) Handles FlowLayoutPanel1.Paint
Dim btn As New Button
Dim table as datatable = Dataset11.Tables("ItemInfo")

For 'i think this will need a looping, but i have no idea how to write'
With btn
.Text = ?? 'text will be the itemName'
.Tag = ?? 'tag will be the itemPrice'
End With
End Sub

i have no idea what to do next, please help.

Answer Source

The problem here aside from adding a control is iterating from a datatable. Datatables contain DataRows. So that is what you want to get to create the the buttons based on the content of your datatable.

Try this:

    Dim btn As New Button
    For Each drow As DataRow In table.Rows
        btn = New Button
        btn.Text = drow.Item("itemName").ToString
        btn.Tag = drow.Item("itemPrice").ToString

Also, you might take into consideration changing the event in which you are adding the controls in the FlowLayoutPanel. You can use a Form_Load event for example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download