我正在尝试在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();
}
}
}
答案 0 :(得分:0)
尝试展开所有列,然后应用绘画。
类似的东西:
private void btnAutoResizeContactNameColumn_Click(object sender, EventArgs e)
{
// Perform Auto Resize on Contact column
this.ultraGrid1.DisplayLayout.Bands[0].Columns["ContactName"].PerformAutoResize();
}