Ak18 LUKA
Ak18 LUKA

Reputation: 29

Show image in datagridview boolean column instead of the 0/1 value

I have a WinForms desktop app with data grid view. It loads data from Sql server and I have a bit column USRstatus in the table. The table columns is as follows:

USRstatus(bit) , USERNAME, USERTYPE

When I load the table in my DataGridView, I want to show images instead of 0/1 values.

The images are in the resources:

Pharm.propreties.recourses.on
Pharm.propreties.recourses.off

EDIT At the load of dgv, I created an image Column and inserted it in

DataGridViewImageColumn IMG =new 
DataGridViewImageColumn();
IMG.name="status";
DGVUsers.Columns.Insert(1,IMG);
DGVUsers.Columns["USRStatus"]. Visible=false;

And then I used for to fill the value of every row depending on the value of the USRstatus value.

for (int i=0;i<DGVUsers.RowCount;i++)
{
      If(Convert.ToByte(DGVUsers.Rows[i].Cells["USRStatus"].Value==1)
       DGVUsers.Rows[i].Cells["status "].Value=Pharma.Propreties.Recourcess.on;
      Else
       DGVUsers.Rows[i].Cells["status"].Value=Pharma.Propreties.Recourcess.off;
} 

It works fine but I want to do it by replacing the whole column, and not creating a new one depending on the other one if that's possible

Upvotes: 1

Views: 1208

Answers (1)

rom_totach
rom_totach

Reputation: 108

You can use the DataGridViewImageColumn in the DataGridView. When you create a new column just choose the type DataGridViewImageColumn. When you want to change the image just set the value.

if ()
    DataGridView.Rows[0].Cells[0].Value = Pharm.Propreties.Recourses.on;
else
    DataGridView.Rows[0].Cells[0].Value = Pharm.Propreties.Recourses.off;

To see if it is on or off you can use the equals method (every type has this):

if (DataGridView.Rows[0].Cells[0].Value.Equals(Pharm.Properties.Resources.on)
{ }

Another way to do this is to use the Tag variable (every winforms control has this - System.Windows.Forms.Control):

DataGridView.Rows[0].Cells[0].Tag = true;

Then, to get its value:

if (DataGridView.Rows[0].Cells.Tag as bool)
{ }

or

if ((bool)DataGridView.Rows[0].Cells.Tag)
{ }

Personally, I like the as bool option more, it is more clear and esthetic.

Another way is to create a new control, but it is way more complicated for this purpose.

Good Luck!

Upvotes: 1

Related Questions