我正在尝试在 datagridviewcell 中显示多色文本,而且我快到了。但是发现双击列分隔符有点问题。
当我双击列分隔符时,部分单元格背景颜色未正确绘制。我忘了用我的代码做什么?请给我建议。
这是我的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MulticoloredGridViewTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Rows.Add("niaz,rahim,azme,niaz,rahim,azme", "123,677,111", "dhaka,dhaka,dhaka");
}
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex >= -1)
{
// Rectangle newRect = new Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 1, e.CellBounds.Width - 1, e.CellBounds.Height - 1);
e.Paint(e.ClipBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentForeground);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
Point startPoint = e.CellBounds.Location;
if (e.Value != null)
{
string[] dataList = e.Value.ToString().Split(',');
foreach (string data in dataList)
{
SizeF tmpSize = e.Graphics.MeasureString(data.Trim(), e.CellStyle.Font);
Rectangle txtRegion = new Rectangle(startPoint, new Size((int)(tmpSize.Width + 3), e.CellBounds.Height));
Color clr = new Color();
if (data.Trim().Contains("rahim"))
clr = Color.Red;
else
clr = Color.Black;
using (SolidBrush br = new SolidBrush(clr))
{
e.Graphics.DrawString(data.Trim(), e.CellStyle.Font, br, txtRegion, StringFormat.GenericDefault);
}
startPoint = new Point(startPoint.X+txtRegion.Width+1, e.CellBounds.Location.Y);
}
e.Handled = true;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
string[] cell = textBox1.Text.Split(',');
string value = dataGridView1.Rows[int.Parse(cell[0])].Cells[int.Parse(cell[1])].Value.ToString();
label1.Text = value;
}
private void dataGridView1_ColumnDividerDoubleClick(object sender, DataGridViewColumnDividerDoubleClickEventArgs e)
{
dataGridView1.Columns[e.ColumnIndex].DividerWidth = dataGridView1.CurrentCell.Value.ToString().Length + 10;
dataGridView1.Invalidate();
}
}
}