C# listbox中如何每一行显示不同的颜色

参见:https://www.it1352.com/532843.html

1、Form中加两句话

public Form1()

    {

      InitializeComponent();

      listBox1.DrawMode = DrawMode.OwnerDrawFixed;

      listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);

2、添加下面这个函数,遇到特定的字符串就会不同的颜色显示了(例如“>>”和“<<”)

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)

    {

      e.DrawBackground();          //先调用基类实现

      if (e.Index < 0)            //form load 的时候return

        return;

      //因为此函数每一个 listItem drawing 都要调用, 所以不能简单的只写

      //e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),e.Font, Brushes.Red, e.Bounds);

      //那样会造成所有item一个颜色           

      //这里是用item字符串是否包含某些词决定的 , 不好

      if (listBox1.Items[e.Index].ToString().Contains(">> "))

      {

        e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),

        e.Font, Brushes.Red, e.Bounds);

      }

      else if (listBox1.Items[e.Index].ToString().Contains("<< "))

      {

        e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),

            e.Font, Brushes.Red, e.Bounds);

      }

      else

      {

        e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),

                e.Font, Brushes.Black, e.Bounds);

      }

    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容