@穆罕默德·巴比克。 要从数据库中为每个类别标签设置随机颜色,您可以按照以下步骤操作:
从数据库中检索类别标签及其相应的以逗号分隔的 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
};
}
}
结果: