开发者

Change Listbox's selected item Backcolor in C#.net

开发者 https://www.devze.com 2022-12-10 14:05 出处:网络
i need to change the backcolor of the selected item in listbox. Can you give me some code example? i\'ve tried add开发者_StackOverflow社区ing DrawItem event but it didnt work for me. Set the listbox\'

i need to change the backcolor of the selected item in listbox. Can you give me some code example? i've tried add开发者_StackOverflow社区ing DrawItem event but it didnt work for me.


Set the listbox's DrawMode to OwnerDrawFixed.

Then assign these events:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    int index = e.Index;
    Graphics g = e.Graphics;
    foreach (int selectedIndex in this.listBox1.SelectedIndices)
    {
        if (index == selectedIndex)
        {
            // Draw the new background colour
            e.DrawBackground();
            g.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
        }
    }

    // Get the item details
    Font font = listBox1.Font;
    Color colour = listBox1.ForeColor;
    string text = listBox1.Items[index].ToString();

    // Print the text
    g.DrawString(text, font, new SolidBrush(Color.Black), (float)e.Bounds.X, (float)e.Bounds.Y);
    e.DrawFocusRectangle();

}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    listBox1.Invalidate();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消