【问题标题】:Creating buttons in runtime from Database field从数据库字段在运行时创建按钮
【发布时间】:2010-11-24 13:34:31
【问题描述】:

我有一个包含 50 条记录的单列表。我想从这些记录中创建 50 个按钮。我如何在 Vb.Net 中做到这一点?

任何帮助将不胜感激。

【问题讨论】:

  • 这是 winforms、asp.net、wpf、silverlight 等吗?列中有什么信息?

标签: vb.net sql-server-2005


【解决方案1】:

假设您的意思是 Winforms:

使用您的数据源(例如 DataTable)并循环其 RowCollection。例如:

Private Sub BtnLoadButtons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLoadButtons.Click
    Dim source As New DataTable("MyButtonTable")
    source.Columns.Add(New DataColumn("MyButtonColumn", GetType(String)))
    For i As Int32 = 1 To 50
        Dim newRow As DataRow = source.NewRow
        newRow("MyButtonColumn") = "Button_" & i
        source.Rows.Add(newRow)
    Next
    'you are loading the above DataTable from SQL-Server, now iterate the rows...'
    For Each row As DataRow In source.Rows
        Dim btn As New Button()
        btn.Name = DirectCast(row("MyButtonColumn"), String)
        btn.Text = btn.Name
        btn.Location = New Point(0, Me.Panel1.Controls.Count * btn.Height)
        AddHandler btn.Click, AddressOf handleButton
        Me.Panel1.Controls.Add(btn)
    Next
End Sub

Private Sub handleButton(ByVal sender As Object, ByVal e As EventArgs)
    Dim btn As Button = DirectCast(sender, Button)
    'do something ...'
End Sub

【讨论】:

  • 优秀。正是我正在寻找的。非常感谢施梅尔特先生。问候
【解决方案2】:

如果您在 Winforms 应用程序中工作,则可以使用 FlowLayoutPanel,因为它会自动为您排序按钮布局:

dim i as integer=1
for each record in Table
    dim btn as new Button
    btn.id = "btn" & i
    i+=1
    Panel1.Controls.add(btn)
next

【讨论】:

  • +1 但您不仅需要使用 FlowLayout。您可以使用 i 相当简单地将按钮放置在位置 x/y 将成为 i 的函数的位置。
猜你喜欢
  • 2020-11-16
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
  • 2018-06-21
  • 2011-08-19
相关资源
最近更新 更多