Home > database >  change color item listbox c#
change color item listbox c#

Time:12-06

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.

CodePudding user response:

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);
}

CodePudding user response:

Well, best idea i have to dont use list box, but use flowLayoutPanel and add usercontrols where you will have labels. flowLayoutPanel works as list of controls witch you can scroll, so we will just create a usercontrol, where we will put label and change the usercontrol background Dont 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);
            
            
        }
  • Related