Dynamically add images and text to cells in the Winform DataGridView column,

Source: Internet
Author: User

Dynamically add images and text to cells in the Winform DataGridView column,

First, the style of the image and text in the second column.

1. You need to override the DataGridViewTextBoxColumn to create a class TextAndImageColumn. cs

  1 using System;  2 using System.Collections.Generic;  3 using System.Linq;  4 using System.Text;  5 using System.Windows.Forms;  6 using System.Drawing;  7   8 namespace DataGridViewTest  9 { 10     public class TextAndImageColumn : DataGridViewTextBoxColumn 11     { 12         private Image imageValue; 13         private Size imageSize; 14  15         public TextAndImageColumn() 16         { 17             this.CellTemplate = new TextAndImageCell(); 18         } 19  20         public override object Clone() 21         { 22             TextAndImageColumn c = base.Clone() as TextAndImageColumn; 23             c.imageValue = this.imageValue; 24             c.imageSize = this.imageSize; 25             return c; 26         } 27  28         public Image Image 29         { 30             get { return this.imageValue; } 31             set 32             { 33                 if (this.Image != value) 34                 { 35                     this.imageValue = value; 36                     this.imageSize = value.Size; 37  38                     if (this.InheritedStyle != null) 39                     { 40                         Padding inheritedPadding = this.InheritedStyle.Padding; 41                         this.DefaultCellStyle.Padding = new Padding(imageSize.Width, 42                     inheritedPadding.Top, inheritedPadding.Right, 43                     inheritedPadding.Bottom); 44                     } 45                 } 46             } 47         } 48         private TextAndImageCell TextAndImageCellTemplate 49         { 50             get { return this.CellTemplate as TextAndImageCell; } 51         } 52         internal Size ImageSize 53         { 54             get { return imageSize; } 55         } 56     } 57  58     public class TextAndImageCell : DataGridViewTextBoxCell 59     { 60         private Image imageValue; 61         private Size imageSize; 62  63         public override object Clone() 64         { 65             TextAndImageCell c = base.Clone() as TextAndImageCell; 66             c.imageValue = this.imageValue; 67             c.imageSize = this.imageSize; 68             return c; 69         } 70  71         public Image Image 72         { 73             get 74             { 75                 if (this.OwningColumn == null || 76            this.OwningTextAndImageColumn == null) 77                 { 78  79                     return imageValue; 80                 } 81                 else if (this.imageValue != null) 82                 { 83                     return this.imageValue; 84                 } 85                 else 86                 { 87                     return this.OwningTextAndImageColumn.Image; 88                 } 89             } 90             set 91             { 92                 if (this.imageValue != value) 93                 { 94                     this.imageValue = value; 95                     this.imageSize = value.Size; 96  97                     Padding inheritedPadding = this.InheritedStyle.Padding; 98                     this.Style.Padding = new Padding(imageSize.Width, 99                    inheritedPadding.Top, inheritedPadding.Right,100                    inheritedPadding.Bottom);101                 }102             }103         }104         protected override void Paint(Graphics graphics, Rectangle clipBounds,105        Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState,106        object value, object formattedValue, string errorText,107        DataGridViewCellStyle cellStyle,108        DataGridViewAdvancedBorderStyle advancedBorderStyle,109        DataGridViewPaintParts paintParts)110         {111             // Paint the base content112             base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,113               value, formattedValue, errorText, cellStyle,114               advancedBorderStyle, paintParts);115 116             if (this.Image != null)117             {118                 // Draw the image clipped to the cell.119                 System.Drawing.Drawing2D.GraphicsContainer container =120                graphics.BeginContainer();121 122                 graphics.SetClip(cellBounds);123                 graphics.DrawImageUnscaled(this.Image, cellBounds.Location);124 125                 graphics.EndContainer(container);126             }127         }128 129         private TextAndImageColumn OwningTextAndImageColumn130         {131             get { return this.OwningColumn as TextAndImageColumn; }132         }133     }134 }

2. Create a new form Form1.cs and drag the control DataGridView to the form. The Code is as follows:

1 using System; 2 using System. collections. generic; 3 using System. componentModel; 4 using System. data; 5 using System. drawing; 6 using System. linq; 7 using System. text; 8 using System. windows. forms; 9 using System. data. sqlClient; 10 11 namespace DataGridViewTest 12 {13 public partial class Form1: Form 14 {15 private static string imagePath = AppDomain. currentDomain. baseDirectory. substring (0, Ap PDomain. currentDomain. baseDirectory. indexOf ("bin") + "Images \"; // list image path 16 public Form1 () 17 {18 InitializeComponent (); 19 InitControlsProperties (); 20} 21 22 private void InitControlsProperties () 23 {24 this. dataGridView1.AutoGenerateColumns = false; 25 TextAndImageColumn ColumnRoleID = new TextAndImageColumn (); 26 ColumnRoleID. dataPropertyName = "RoleID"; 27 ColumnRoleID. defaultCellStyle. al Ignment = maid. middleLeft; 28 ColumnRoleID. name = "RoleID"; 29 ColumnRoleID. headerText = "permission ID"; 30 ColumnRoleID. width = 200; 31 this. dataGridView1.Columns. add (ColumnRoleID); 32 33 this. dataGridView1.AutoGenerateColumns = false; 34 TextAndImageColumn ColumnRoleName = new TextAndImageColumn (); 35 ColumnRoleName. dataPropertyName = "RoleName"; 36 ColumnRoleName. defaultCellStyl E. alignment = maid. middleLeft; 37 ColumnRoleName. name = "RoleName"; 38 ColumnRoleName. headerText = "permission name"; 39 ColumnRoleName. width = 100; 40 this. dataGridView1.Columns. add (ColumnRoleName); 41 42 this. dataGridView1.AutoGenerateColumns = false; 43 TextAndImageColumn ColumnDescription = new TextAndImageColumn (); 44 ColumnDescription. dataPropertyName = "Description"; 45 ColumnD EIP. defaultCellStyle. alignment = maid. middleLeft; 46 ColumnDescription. name = "Description"; 47 ColumnDescription. headerText = "Description"; 48 ColumnDescription. width = 150; 49 this. dataGridView1.Columns. add (ColumnDescription); 50} 51 52 private void Form1_Load (object sender, EventArgs e) 53 {54 string strConn = "Data Source = XIAN-PC; Initial Catalog = ReportServer; Persist Se Curity Info = True; User ID = sa; Password = sa "; 55 SqlConnection conn = new SqlConnection (strConn); 56 string strSql =" select * from Roles "; 57 SqlCommand cmd = new SqlCommand (strSql, conn); 58 SqlDataAdapter adapter = new SqlDataAdapter (cmd); 59 DataSet ds = new DataSet (); 60 conn. open (); 61 adapter. fill (ds, "Roles"); 62 conn. close (); 63 this. dataGridView1.DataSource = ds. tables ["Roles"]; 64} 65 66 p Rivate void maid (object sender, maid e) 67 {68 # region second column 69 if (e. columnIndex = 1) 70 {71 TextAndImageCell cell = maid [e. rowIndex]. cells [e. columnIndex] as TextAndImageCell; 72 if (cell! = Null & e. Value! = Null) 73 {74 try 75 {76 string ajzt = cell. value. toString (); 77 string path = imagePath; 78 switch (ajzt) 79 {80 case "publisher": 81 path + = "1.png"; 82 break; 83 case" Viewer ": 84 path + = "2.png"; 85 break; 86 default: 87 path + =" 3.png"; 88 break; 89} 90 cell. image = GetImage (path); 91} 92 catch (Exception ex) 93 {94 95} 96} 97} 98 # endregion 99} 100 101 public System. drawing. image GetImage (string path) 102 {103 return System. drawing. image. from file (path); 104} 105 106} 107}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.