在 BackColor 文本标签 C# windows 窗体上动态生成新颜色

问题描述 投票:0回答:1

我在餐厅的 POS 系统中工作,为了促进排序过程,我希望所有类型的类别都有不同的颜色。 image of result

我想要一个可以生成随机背景颜色的代码,然后让每个项目都是统一的颜色

c# windows visual-studio user-interface background-color
1个回答
1
投票

@穆罕默德·巴比克。 要从数据库中为每个类别标签设置随机颜色,您可以按照以下步骤操作:

从数据库中检索类别标签及其相应的以逗号分隔的 RGB 颜色值。

解析 RGB 颜色值并将其转换为 Color 对象。

为每个类别标签生成随机颜色。

为类别标签分配随机颜色。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Load += Form1_Load;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        // Assuming you have a method to retrieve category labels and their colors from the database
        Dictionary<string, string> categoryColors = GetCategoryColorsFromDatabase();

        // Generate random colors for each category label
        Random random = new Random();
        int top = 10;
        Label label;
        foreach (var categoryLabel in categoryColors.Keys)
        {
            // Parse the RGB color value from the database
            string[] rgbValues = categoryColors[categoryLabel].Split(',');
            int red = int.Parse(rgbValues[0]);
            int green = int.Parse(rgbValues[1]);
            int blue = int.Parse(rgbValues[2]);

            // Create a Color object using the parsed RGB values
            Color color = Color.FromArgb(red, green, blue);

            label = new Label();
            label.Text = categoryLabel;
            label.BackColor = color;
            label.Width = 100;
            label.Height = 50;
           
            label.Location = new Point(50, top);
            top += 80;
            Controls.Add(label);
        }
    }

    private Dictionary<string, string> GetCategoryColorsFromDatabase()
    {
        // Simulated database query
        return new Dictionary<string, string>
        {
            { "Category 1", "150,250,70" },
            { "Category 2", "100,200,150" },
            { "Category 3", "200,100,50" }
            // Add more category labels and their colors as needed
        };
    }
}

结果:

© www.soinside.com 2019 - 2024. All rights reserved.