vbnewbie vbnewbie - 1 month ago 8
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

dataset

Private Sub temp_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.ItemInfoTableAdapter1.Fill(DataSet11.ItemInfo)
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
Me.FlowLayoutPanel1.Controls.Add(btn)
Next
End Sub


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

Answer

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
        FlowLayoutPanel1.Controls.Add(btn)
    Next

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.