Dynamically generate Button from database value in Windows Application using C# and VB.Net

Last Reply 4 months ago By pandeyism

Posted 4 months ago

I have list of buttons lets say

Button1 Button2 etc.

And I have table which will store restaurant table number, in my select query will display all the table like

3

4 etc.

Now I want bind all the buttons with table numbers  like

1              2            3             4

5              6            7              8

    Public Sub New()
        InitializeComponent()
        AddButtons()
    End Sub

    Private Sub AddButtons()
        Dim xPos As Integer = 0
        Dim yPos As Integer = 0
        Dim n As Integer = 0
        ' Declare and Initialize one variable    
        Dim btnArray(35) As System.Windows.Forms.Button
        For i As Integer = 0 To 35
            btnArray(i) = New System.Windows.Forms.Button
        Next i

        While (n < 35)
            With (btnArray(n))
                .Tag = n + 1 ' Tag of button
                .Width = 75 ' Width of button
                .Height = 25 ' Height of button
                '.UseVisualStyleBackColor = True
                .Dock = DockStyle.Fill
                .FlatStyle = FlatStyle.Flat
                If (n = 13) Then ' Location of second line of buttons:
                    xPos = 0
                    yPos = 20
                End If            
            .Top = yPos
                TableLayoutPanel1.Controls.Add(btnArray(n)) ' Let panel hold the Buttons
                xPos = xPos + .Width ' Left of next button
                            
                AddHandler .Click, AddressOf Me.ClickButton
                n += 1
            End With
        End While
    End Sub 

 

Posted 4 months ago

Hi satabeach,

Refer below sample.

Code

C#

private void Form1_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Rows.Add(1);
    dt.Rows.Add(2);
    dt.Rows.Add(3);
    dt.Rows.Add(4);
    dt.Rows.Add(5);
    dt.Rows.Add(6);
    dt.Rows.Add(7);
    dt.Rows.Add(8);
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        Button btn = new Button();
        btn.Text = dt.Rows[i]["Name"].ToString();
        tableLayoutPanel1.Controls.Add(btn);
    }
}

VB.Net

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim dt As DataTable = New DataTable()
    dt.Columns.Add("Name")
    dt.Rows.Add(1)
    dt.Rows.Add(2)
    dt.Rows.Add(3)
    dt.Rows.Add(4)
    dt.Rows.Add(5)
    dt.Rows.Add(6)
    dt.Rows.Add(7)
    dt.Rows.Add(8)

    For i As Integer = 0 To dt.Rows.Count - 1
        Dim btn As Button = New Button()
        btn.Text = dt.Rows(i)("Name").ToString()
        tableLayoutPanel1.Controls.Add(btn)
    Next
End Sub

Screenshot