简体   繁体   中英

How can I display icon in datagridview specific cell instead of True or false of boolean type, in C# winform?

How can I display icon in datagridview specifik cell instead of True or false of boolean type? I have those two images in my Project Resources (I don't know if its is best place to store them). It's like thumbs up and thumbs down images. Thank you in advance! Here is my code I'am trying fix but offcourse do not working

var result = (from u in db.Analys
              join d in db.Department on u.deptId equals d.deptId 
              select new
             {
               AnalysId = u.Id
               Department = d.DepartmenName,                                           
               Accept= u.accept == true ? Resources.thumbsUp : Resources.thumbsDown   

           }).ToList();
           if (result != null)
           {
             daraGridViewResult.DataSource = null;
             daraGridViewResult.DataSource = result;

           }

On the CellPainting event of your grid, you can add a code like this:

 e.Paint(e.CellBounds, DataGridViewPaintParts.All);

 var w = Properties.Resources.yes.Width;
 var h = Properties.Resources.yes.Height;
 var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
 var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;

 e.Graphics.DrawImage(image, new Rectangle(x, y, w, h));

where "image" is the image you want to display instead of "true" or "false".

Keep in mind that this code will execute for every single cell in the datagrid. You need to control that this only applies to cells on your boolean column.

EDIT:

 if (e.ColumnIndex == yourGrid.Columns["Accept"].Index)
 {
      e.Paint(e.CellBounds, DataGridViewPaintParts.All);

      var w = Properties.Resources.yes.Width;
      var h = Properties.Resources.yes.Height;
      var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
      var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;

      e.Graphics.DrawImage(image, new Rectangle(x, y, w, h));
 } //if

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM