简体   繁体   中英

change color item listbox c#

I have created a ListBox to which I add elements during code compilation. and I want to record its color when adding one element (so that each added element has a different color)

listBox1.Items.Add(string.Format("Місце {0} | В роботі з {1} | ({2} хв)", temp[7].Substring(6, 4), temp[8].Substring(11, 5), rezult));   `

I tried everywhere possible to embed this change

BackColor = Color.Yellow;ForeColor = Color.Yellow;

I am working with listbox because I have seen so many answers about ListView .

Set the listbox DrawMode to either OwnerDrawFixed or OwnerDrawVariable and set this as the DrawItem event handler:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e){
    if(e.Index == 1) e.DrawBackground(); //use e.Index to see if we want to highlight the item
    else e.Graphics.FillRectangle(new SolidBrush(Color.Yellow), e.Bounds); //This does the same thing as e.DrawBackground but with a custom color
    e.DrawFocusRectangle();
    if(e.Index < 0) return;
    TextRenderer.DrawText(e.Graphics, (string)listBox1.Items[e.Index], listBox1.Font, e.Bounds, listBox1.ForeColor, TextFormatFlags.Left);
}

Well, best idea I have is to not use list box, but flowLayoutPanel and add usercontrols where you will have labels.

flowLayoutPanel works as list of controls which you can scroll, so we will just create a usercontrol , where we will put label and change the usercontrol background Don't forget to turn on the AutoScroll feature to flowLayoutPanel , otherwise the scroll bar wont work and wont even show up.

If you want to be able to be clickable just add to the label click event.

 public void CreateItem(Color OurColor, string TextToShow)
        {
    
    
            Label OurText = new Label()
            {
                Text = "TextToShow",
                Font = new Font("Segoe UI", 8f),
                Location = new Point(0, 0),
                AutoSize = true,
    
            };
    
            UserControl OurUserControl = new UserControl();
    
            OurUserControl.Size = new Size((int)((double)flowLayoutPanel1.Width * 0.9) , OurText.Font.Height);
    
            OurUserControl.BackColor = OurColor;
            OurUserControl.Controls.Add(OurText);
    
            flowLayoutPanel1.Controls.Add(OurUserControl);
            
            
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM