代码中设置指定字符串中的字体大小和粗体及红色的颜色后通过单击按钮返回到windows窗体上的Datagridview控件上显示,这个如何做呢
我不是要求DataGridView控件上设置的,要求代码中设置的。
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim str2 As String = "012345"
Me.DataGridView1.Rows.Add(str2)
End Sub
End Class
------解决方案--------------------
DataGridView重绘单元格中某些字体颜色,大小
分类: c#.net /vb.net 2011-09-13 07:02 72人阅读 评论(0) 收藏 举报
view plain
主要通过对单元格进行重绘,改变元单元格字体大小和颜色
view plain
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
base.OnCellPainting(e);
if (e.Value != null)
{
string cellWord = e.Value.ToString();//单元格原本内容
string keyWord = e.Value.ToString();//要改变的单元格关键字内容
Rectangle cellRect = e.CellBounds;//默认单元格
Rectangle keyRect = e.CellBounds;//单元格内容区域,默认定义为单元格大小
float fontSizeWeight = 96 / (72 / e.CellStyle.Font.Size); // 字体实际像素宽度
float fontSizeHeight = 96 / (72 / e.CellStyle.Font.Size); // 字体实际像素高度
//关键字的坐标
keyRect.X += cellWord.Substring(0, cellWord.IndexOf(keyWord)).Length * (int)(fontSizeWeight / 2);
keyRect.Y += (e.CellBounds.Height - (int)fontSizeHeight) / 2;
//原文本的Y坐标
cellRect.Y = keyRect.Y;
using (Brush foreColor = new SolidBrush(e.CellStyle.ForeColor), fontColor = new SolidBrush(this.FontColor))
{
//绘制背景色
e.PaintBackground(e.ClipBounds, false);
//绘制背景色(被选中状态下)
if (e.State == (DataGridViewElementStates.Displayed
------解决方案--------------------
DataGridViewElementStates.Selected
------解决方案--------------------
DataGridViewElementStates.Visible))
e.PaintBackground(e.ClipBounds, true);
//分别绘制原文本和现在改变颜色的文本
e.Graphics.DrawString(cellWord, this.Font, foreColor, cellRect, StringFormat.GenericDefault);
e.Graphics.DrawString(keyWord, this.Font, fontColor, keyRect, StringFormat.GenericDefault);
//提交事务
e.Handled = true;
}
}
}
定义该重绘控件的字体,前景色和背景图片
view plain
#region properties
/// <summary>
/// 获取或设置该控件下显示字体的大小.
/// </summary>
[Browsable(true)]
[DefaultValue(typeof(Font), "宋体,9"), Description("获取或设置该控件下显示字体的大小.")]
public override Font Font
{
get { return this._font; }