In this article I will explain with an example, how to create dynamic
CheckBoxes from Database in
Windows Forms (WinForms) Application using C# and VB.Net.
The dynamic CheckBoxes will be created inside FlowLayoutPanel and will be assigned with dynamic CheckChanged event handler.
Database
I have made use of the following table Fruits with the schema follows.
The Fruits table has the following records.
Note: You can download the database table SQL by clicking the download link below.
Form Design
The Form consists of a FlowPanelLayout.
Then dynamic CheckBoxes will be added to the FlowLayoutPanel control.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Create Dynamic CheckBox from Database in Windows Application
Inside the Form Load event handler, first the list of Fruits is fetched from the Database Table and then a loop is executed over the list of Fruits.
Inside the loop,
CheckBox control is dynamically created and it is assigned with a
CheckChanged event handler.
Finally dynamically created
CheckBox is added to the
FlowLayoutPanel control.
Inside the
CheckChanged event handler, first the
checked or
unchecked CheckBox is referenced and if the
CheckBox is checked, its Text is shown using
Message Box.
C#
private void PopulateCheckBoxes()
{
string query = "SELECT FruitName FROM Fruits";
string constr = @"Data Source= .\SQL2019;Initial Catalog=AjaxSamples;uid=sa;pwd=pass@123";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
//Fill the DataTable with records from Table.
DataTable dt = new DataTable();
sda.Fill(dt);
//Loop and add CheckBoxes toFloyLayoutPanel.
foreach (DataRow row in dt.Rows)
{
CheckBox chk = new CheckBox();
chk.Width = 80;
chk.Text = row["FruitName"].ToString();
chk.CheckedChanged += new EventHandler(CheckBox_Checked);
checkBoxPanel.Controls.Add(chk);
}
}
}
}
private void CheckBox_Checked(object sender, EventArgs e)
{
CheckBox chk = (sender as CheckBox);
if (chk.Checked)
{
MessageBox.Show("You selected: " + chk.Text);
}
}
VB.Net
Private Sub PopulateCheckBoxes()
Dim query As String = "SELECT FruitName FROM Fruits"
Dim constr As String = "Data Source= .\SQL2019;Initial Catalog=AjaxSamples;uid=sa;pwd=pass@123"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
For Each row As DataRow In dt.Rows
Dim chk As CheckBox = New CheckBox()
chk.Width = 80
chk.Text = row("FruitName").ToString()
AddHandler chk.CheckedChanged, AddressOf CheckBox_Checked
checkBoxPanel.Controls.Add(chk)
Next
End Using
End Using
End Sub
Private Sub CheckBox_Checked(ByVal sender As Object, ByVal e As EventArgs)
Dim chk As CheckBox = (TryCast(sender, CheckBox))
If chk.Checked Then
MessageBox.Show("You selected: " & chk.Text)
End If
End Sub
Screenshot
Downloads