改变Listbox中的字体颜色

当用ListBox来作输出显示的时候,有时需要针对不同的输出显示不同的颜色,比如当用ListBox来作告警输出的时候,需要根据不同的告警等级来显示不同的颜色,以达到醒目的作用,其实用ListBox来做这种事情很容易。
首先把ListBox的DrawMode设为OwnerDrawFixed或是OwnerDrawVariable,然后在ListBox的DrawItem事件中加入下面的代码

private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
Brush FontBrush = null;
ListBox listBox = sender as ListBox;
if (e.Index > -1)
{
switch (listBox.Items[e.Index].ToString())
{
case "Critical": FontBrush = Brushes.Brown; break;
case "Major": FontBrush = Brushes.Red; break;
case "Minor": FontBrush = Brushes.Orange; break;
case "Warning": FontBrush = Brushes.Yellow; break;
default: FontBrush = Brushes.Black; break;
}
e.DrawBackground();
e.Graphics.DrawString(listBox.Items[e.Index].ToString(), e.Font, FontBrush, e.Bounds);
e.DrawFocusRectangle();
}
}



即可。
完整的程序代码如下:以下代码在vs2005中测试通过

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ListBoxDataGrid
{
public partial class ListBoxForm : Form
{
public ListBoxForm()
{
InitializeComponent();
}
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
Brush FontBrush = null;
ListBox listBox = sender as ListBox;
if (e.Index > -1)
{
switch (listBox.Items[e.Index].ToString())
{
case "Critical": FontBrush = Brushes.Brown; break;
case "Major": FontBrush = Brushes.Red; break;
case "Minor": FontBrush = Brushes.Orange; break;
case "Warning": FontBrush = Brushes.Yellow; break;
default: FontBrush = Brushes.Black; break;
}
e.DrawBackground();
e.Graphics.DrawString(listBox.Items[e.Index].ToString(), e.Font, FontBrush, e.Bounds);
e.DrawFocusRectangle();
}
}
private void button_Click(object sender, EventArgs e)
{
if (!textBox.Text.Length.Equals(0))
listBox.Items.Add(textBox.Text);
}
}
}



转自:http://www.cnblogs.com/aaliujing/archive/2007/01/29/633689.html
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值