rul3z rul3z - 2 months ago 62
C# Question

Use DataGridView CheckBox Column for a string data column

I have this table in database:

applicant | module | date | approvation |
xxxx xxxx xxxx xxxxxxx
yyyy yyyy yyyy yyyyyyy
tttt tttt tttt ttttttt


I have this db table. After query I assign
DataTable
to my
DataGridView.DataSource
:

QueryAssist qa = new QueryAssist();
DataTable dt = new DataTable();
dt = qa.runQuery('myquery');

dgvApprovazione.DataSource = dt;
dgvApprovazione.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);

// modify, transform 2nd column in cellLink
foreach (DataGridViewRow row in dgvApprovazione.Rows)
{
row.Cells[1] = new DataGridViewLinkCell();
}


Now I want to transform column
approvation
that is a string
approved
or
not approved
and show a check box instead.

if value of this cell is
approved
check box is checked and not modified (onlyread).

something similar:

foreach (DataGridViewRow row in dgvApprovazione.Rows)
{
if (row.Cells[3].Value.ToString().Equals("APPROVED"))
{
row.Cells[3] = new DataGridViewCheckBoxCell();
}
}


I have a problem to implement ... help me.

It's possible ? How?

recapping:

I want to change a column that value contain is a text/string (approved or not approved ) in checkbox (checked or unchecked)

Sorry for bad english ..

Good alternatives?

Answer

To store yes/no or on/off or true/false values in database, it's better to use bit data type in sql server, but using a DataGridViewCheckBoxColumn you can show and edit also a string column by setting TrueValue and FalseValue properties.

In the below example I supposed you have a nullable column in database which needs to store values as APPROVED or NOTAPPROVED as nvarchar(50) and you need to edit those values using DataGridViewCheckBoxColumn.

To do so, you should add your column this way using designer or code:

var column1 = new DataGridViewCheckBoxColumn();   
column1.Name = "column1";                         //Name of column
column1.HeaderText= "Is Approved";                //Title of column
column1.DataPropertyName = "approvation";         //Name of filed in database
column1.TrueValue = "APPROVED";                   //True value
column1.FalseValue = "NOTAPPROVED";               //False Value
this.dataGridView1.Columns.Add(column1);

This way you show approved or not approved as check boxes, also you are able to edit those values using check box.

If you don't need to edit them and only want to show them, you can set read only property of the column true.