【问题标题】:how to change listbox item color c# based on its index如何根据其索引更改列表框项目颜色c#
【发布时间】:2014-06-22 09:19:01
【问题描述】:

我想根据它的索引更改 ListBox 项的颜色。 我有一个 TextBox...当用户输入索引号时,我想更改列表框中相应索引的文本颜色

例如:当用户点击一个按钮时,会发生这样的事情:

    private void button1_Click(object sender, EventArgs e)
            {
                setcolor(int.Parse(textBox1.Text));
            }

我想创建这样的 setcolor 函数。 Listview 不适合我。

【问题讨论】:

  • 你能告诉我们你的代码吗?
  • 在下面查看我的答案。

标签: c# forms


【解决方案1】:

您需要处理ListBoxDrawItem 事件来绘制具有指定color 的Items

注意:在下面的代码中,我用Green改变了ListBox项的颜色

试试这个:

int itemIndex = -1;
public Form1()
{
  InitializeComponent();
  this.listBox1.DrawItem += new            
          System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);
}

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    Graphics g = e.Graphics;
    if(e.Index == itemIndex )
    {
        g.FillRectangle(new SolidBrush(Color.Green), e.Bounds);
    }
    else
    {
        g.FillRectangle(new SolidBrush(Color.White), e.Bounds);
    }
    ListBox lb = (ListBox)sender;
    g.DrawString(listBox1.Items[e.Index].ToString(), e.Font,
          new SolidBrush(Color.Black), new PointF(e.Bounds.X, e.Bounds.Y));
    e.DrawFocusRectangle();
}

private void button1_Click(object sender, EventArgs e)
{
    setcolor(int.Parse(textBox1.Text));
}

void setcolor(int index)
{ 
    itemIndex = index;
    listBox1.DrawMode = DrawMode.Normal;
    listBox1.DrawMode = DrawMode.OwnerDrawFixed;
}

【讨论】:

  • 对不起...所有项目现在都是绿色的!
  • @user3759960:你能发布你的代码吗?因为上面的代码对我来说很好。
  • @user3759960:不客气 :) 很高兴为您提供帮助。
猜你喜欢
  • 2011-10-17
  • 1970-01-01
  • 2020-03-09
  • 2022-01-02
  • 2011-11-22
  • 1970-01-01
  • 2015-05-28
  • 2011-07-01
  • 1970-01-01
相关资源
最近更新 更多