How to Display Records with CheckBox Column in DatagridView Using C#
Submitted by janobe on Tuesday, September 10, 2019 - 21:31.
In this tutorial, I’m going to teach you How to Display Records with CheckBox Column in DatagridView Using C#. This program illustrates how to retrieve data from the database and will be displayed in the datagridview with a corresponding checkbox column. The checkbox column is auto-generated and it can be found in the first column of the datagridview.
The complete source code is included. You can download it and run it on your computer.
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.
Creating a Database
Go to localhost/phpMyAdmin the create a database and named it “profile” After that, execute the following query to create a table and insert some data in the table.- (4, 'Test', 'Female', 'Test'),
- (5, 'test2', 'Male', 'Test2');
Creating Application
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application for c#.
Step 2
Do the form just like shown below.
Step 3
Add MySQL.Data.dllStep 4
Press F7 to open the code editor. In the code editor, add a namespace to accessMySQL
libraries.
- using MySql.Data.MySqlClient;
Step 5
Create a connection between MySQL Database and C#. After that, Initialize all the classes and variables that are needed.- MySqlConnection con = new MySqlConnection("server=localhost;user id=root;password=;database=profile;sslMode=none");
- MySqlCommand cmd;
- MySqlDataAdapter da;
- DataTable dt;
- String sql;
Step 6
Create a method for creating a checkbox column.- private void createCheckbox()
- {
- //'set a variable as a checkbox column in the DataGridView
- //'set the width of the column in the DataGridView
- chkbox.Width = 40;
- //'Adding the checkbox column in the DataGridView
- dataGridView1.Columns.Add(chkbox);
- //'set the rows header to invisible
- dataGridView1.RowHeadersVisible = false;
- }
Step 7
Create a method for displaying records with a checkbox column in the datagridview.- private void loaddata()
- {
- try
- {
- sql = "SELECT * FROM `profile`";
- con.Open();
- cmd.Connection = con;
- cmd.CommandText = sql;
- da.SelectCommand = cmd;
- da.Fill(dt);
- //'adding a checkbox column in the datagridview
- createCheckbox();
- //'display the data from the database to the datagridview
- dataGridView1.DataSource = dt;
- }
- catch(Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- finally
- {
- con.Close();
- da.Dispose();
- }
- }
Step 8
Execute the loaddata()
method in the first load of the form.
- private void Form1_Load(object sender, EventArgs e)
- {
- loaddata();
- }
Add new comment
- 807 views