In this post, we will see how we can add a custom Checkbox
column to an existing DataGridView
in Windows Forms. Generally, when you assign a data source to the DataGridView
and the data source contains a “bit
” column or “bool
” column, DataGridView
automatically converts it into a Checkbox
column. However, at times, we need to provide an extra checkbox
column to the end-user so that they can select/un-select records using the same. This post will help you add a custom checkbox to your DataGridView
.
This post assumes the name of the DataGridView
control as gridRecord
s and LoadGrid()
function assigns the data source to the DataGridView
.
private void LoadGrid()
{
gridRecords.Columns.Clear();
gridRecords.DataSource = GetDataFromDatabase();
if(gridRecords.Columns.Count > 0)
AddCheckBoxColumn();
}
private void AddCheckBoxColumn()
{
DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
doWork.Name = "Select";
doWork.HeaderText = "Select";
doWork.FalseValue = 0;
doWork.TrueValue = 1;
gridRecords.Columns.Insert(0, doWork);
}
In the above code, we first set the DataSource
of datagridview
to the data that has been brought from DB. Before assigning the DataSource
, we ensure that we clear the column collection of the DataGridView
so that the checkbox
column is not added multiple times. Once the DataSource
is set, we check for column count and call a function that adds the custom checkbox
to the beginning of the DataGridView
.
Hope you like this post.
A passionate developer with over 10 years of experience and building my software company code by code. Experience withMS Technologies like .Net | MVC | Xamarin | Sharepoint | MS Project Server and PhP along with open source CMS Systems like Wordpress/DotNetNuke etc.
Love to debug problems and solve them. I love writing articles on my website in my spare time. Please visit my Website for more details and subscribe to get technology related tips/tricks. #SOreadytohelp