如何动态创建用户控件?

时间:2016-11-03 06:35:38

标签: sql database vb.net

我的winform中有一个flowlayoutpanel, 我想在加载表单时向flowlayoutpanel添加一些按钮, 按钮的数量取决于我的数据集中存在多少项(行)

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

我不知道接下来该做什么,请帮忙。

1 个答案:

答案 0 :(得分:0)

除了添加控件之外,此处的问题是从datatable 迭代Datatables包含DataRows。因此,您希望根据datatable的内容创建按钮。

试试这个:

    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

此外,您可能会考虑更改FlowLayoutPanel中添加控件的事件。例如,您可以使用Form_Load事件。