日期:2014-05-18  浏览次数:21550 次

C#,怎么设置listbox文本的颜色?
Winform的
C# code
设置this.listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            string s = this.listBox1.Items[e.Index].ToString();
            if (s.Contains("初始化成功"))
            {
                e.Graphics.DrawString(s, this.Font, Brushes.Green,e.Bounds);
            }
            else if (s.Contains("初始化失败"))
            {
                e.Graphics.DrawString(s, this.Font, Brushes.Red, e.Bounds);
            }
            else
                e.Graphics.DrawString(s,this.Font,new SolidBrush(this.ForeColor),e.Bounds);


        }


网上有找到上面的代码,但不知道怎么用。
我要的效果是当选项里的某一行的值与给出的值相等时,就变成红色。

比较菜,请详细些,谢谢。


------解决方案--------------------
C# code

        private void Form1_Load(object sender, EventArgs e)
        {
            this.listBox1.DrawMode = DrawMode.OwnerDrawFixed;
            this.listBox1.Items.Add("aa");
            this.listBox1.Items.Add("bb");
            this.listBox1.Items.Add("cc");
            this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);
        }

        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            string s = this.listBox1.Items[e.Index].ToString();
            if (s.Contains("cc"))
            {
                e.Graphics.DrawString(s, this.Font, Brushes.Red, e.Bounds);
            }
            else
                e.Graphics.DrawString(s, this.Font, new SolidBrush(this.ForeColor), e.Bounds);

        }