|
In this article I will show you that how to check status of checkbox in
datagridview that is it is checked or not. If checkbox in datagridview is
checked then a message box display which have true and if checkbox in
datagridview is unchecked then a message box display which have false value.
To complete this article drag and drop datagridview in your windows forms. Then
on the load event of form write down following code to bind some values in
datagrid view.
///
<summary>
/// At the load event
of form create a DataTable object
/// and add two
columns in that table. Data type of first
/// column must be
bool and second is string. When You
/// bind the values of
this datatable to datagrid then you
/// see that that column
whose data type is bool is converted
/// into checkbox in
datagridview and it have value true then
/// it is checked and
if it has false then it is unchecked.
/// Below code
explains that how to create DataTable object
/// and how to bind
that data in gridview.
///
</summary>
private void
Form1_Load(object sender,
EventArgs e)
{
DataTable dt =
new DataTable();
//Creating data table object.
dt.Columns.Add("Status",
typeof(bool));
//Adding column in datatable and defining its datatype as a bool.
dt.Columns.Add("Value",
typeof(string)); //Adding
another column in datatable.
string[] data = {
"AAA", "BBB",
"CCC", "DDD",
"EEE" };
//Creating an array of type string.
bool[] status = {
true, true,
false, false,
false };
//Creating an array of type bool.
//Adding rows and value in DataTable.
for (int
i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["Status"] = status[i];
dr["Value"] = data[i];
dt.Rows.Add(dr);
}
dataGridView1.DataSource = dt;
//Binding DataTable values in GridView.
}
After binding values in DataGridView on the
CellContentClick event of
datagridview write down following code to display value of datagridview
checkbox.
///
<summary>
/// This event raised
when we click on cell's content.
/// Here I will show a
message box containing true and
/// false value when
checkbox of datagridview is checked
/// or unchecked
accordingly.
///
</summary>
private void
dataGridView1_CellContentClick(object sender,
DataGridViewCellEventArgs e)
{
//This condition will make sure that this code
execute if and only if checkbox cell is clicked.
if (e.ColumnIndex ==
dataGridView1.Columns["Status"].Index) //Checking
index of checkbox column is equal to clickable cell index.
{
dataGridView1.EndEdit();
//Stop editing of cell.
MessageBox.Show("0 = " +
dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
//Displaying value of that cell which is either true or false in this case.
}
}
Following snapshot will display result
When form is loaded the it display two columns in datagridview with some values.
When you click on checked checkbox then it will display a message box with true
value and when you click on unchecked checkbox then it will display a message
box with false value.
Thanks.
|