1、DataGridView 中在同一个单元格中显示图片和文字要在同一个单元格中显示图片和文字,在网上找了很久,总的来说有这两种方法,第一种就是进行控件的扩展,http:/ ,第二种方法就是用 DataGridView 中的 CellPainting 事件来进行单元格的重新绘制(网上很多人用这个事件处理单元格的合并) ,用这种方法需要注意几个问题,代码如下:private void dgvData_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)if (e.RowIndex = 0 string strExtensio
2、n = this.dgvData.Rowse.RowIndex.Cells“file_Extension“.Value.ToString();string strFileName = this.dgvData.Rowse.RowIndex.Cells“file_Name“.Value.ToString();Image image;string imagePath = Application.StartupPath;if (strExtension = “doc“ | strExtension = “docx“)image = Image.FromFile(imagePath + “Images
3、FileImagedoc.gif“);else if (strExtension = “txt“)image = Image.FromFile(imagePath + “ImagesFileImagetxt.gif“);else if (strExtension = “xls“ | strExtension = “xlsx“)image = Image.FromFile(imagePath + “ImagesFileImagexls.gif“);elseimage = Image.FromFile(imagePath + “ImagesFileImagewz.bmp“);/定义显示图片的矩形R
4、ectangle newRect = new Rectangle(e.CellBounds.X + 2, e.CellBounds.Y + 2, e.CellBounds.Height - 6,e.CellBounds.Height - 6);using (Brush gridBrush = new SolidBrush(this.dgvData.GridColor)using (Pen gridLinePen = new Pen(gridBrush, 2)Font newFont = new Font(“宋体“, 9, FontStyle.Regular);/自定义字体/判断当前行是否为选中
5、行,如果为选中行,则要修改图片的背景色和文字的字体颜色if (dgvData.CurrentRow.Index = e.RowIndex)using (Brush backColorBrush = new SolidBrush(Color.FromArgb(051,153,255)/以背景色填充单元格e.Graphics.FillRectangle(backColorBrush, e.CellBounds);/画单元格的边界线Point p1 = new Point(e.CellBounds.Left + e.CellBounds.Width, e.CellBounds.Top);Point
6、p2 = new Point(e.CellBounds.Left + e.CellBounds.Width, e.CellBounds.Top + e.CellBounds.Height);Point p3 = new Point(e.CellBounds.Left, e.CellBounds.Top + e.CellBounds.Height);Point ps = new Point p1, p2, p3 ;e.Graphics.DrawLines(gridLinePen, ps);/在规定的矩形内以现有的图片进行填充e.Graphics.DrawImage(image, newRect)
7、;/写入字符串e.Graphics.DrawString(strFileName.ToString(), newFont, Brushes.White,e.CellBounds.Left + 20, e.CellBounds.Top + 5, StringFormat.GenericDefault);e.Handled = true;elseusing (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor)e.Graphics.FillRectangle(backColorBrush, e.CellBounds);Point
8、p1 = new Point(e.CellBounds.Left + e.CellBounds.Width, e.CellBounds.Top);Point p2 = new Point(e.CellBounds.Left + e.CellBounds.Width, e.CellBounds.Top + e.CellBounds.Height);Point p3 = new Point(e.CellBounds.Left, e.CellBounds.Top + e.CellBounds.Height);Point ps = new Point p1, p2, p3 ;e.Graphics.Dr
9、awLines(gridLinePen, ps);e.Graphics.DrawImage(image, newRect);e.Graphics.DrawString(strFileName.ToString(), e.CellStyle.Font, Brushes.Black,e.CellBounds.Left + 20, e.CellBounds.Top + 5, StringFormat.GenericDefault);e.Handled = true;方法比较死板,有这么几个问题,第一个就是它的触发问题,在实际的运行中发现,很多情况下都会触发,例如点击单元格事件,选中项改变事件(SelectionChanged)等,都会在这些事件处理完成之后,自动触发 CellPainting 事件,很不理解。第二个问题就是事件默认的画图模板区域就是整个 Cell,所以即便可以定义 Image 的矩形区域大小,但是 Cell 的实际 Value 还是会被覆盖掉。