You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows Forms:根据SQL条件设置ListBox列表项的颜色

Windows Forms ListBox 按MTBF值设置项颜色解决方案

原生ListBox不支持单独设置列表项的颜色,我们可以通过自绘项的方式实现需求,无需切换到ListView。以下是具体实现步骤和代码:

1. 定义产品数据类

创建包含产品名称和MTBF值的类,让每个ListBox项能关联对应的MTBF数据:

public class Product
{
    public string Name { get; set; }
    public int MTBF { get; set; }

    // 重写ToString,让ListBox显示产品名称
    public override string ToString()
    {
        return Name;
    }
}

2. 配置ListBox自绘模式

在窗体构造函数(或设计器)中开启ListBox的自绘模式,并绑定自绘事件:

public FormsProducts()
{
    InitializeComponent();
    // 开启自绘模式
    listBoxProducts.DrawMode = DrawMode.OwnerDrawFixed;
    // 绑定自绘事件
    listBoxProducts.DrawItem += ListBoxProducts_DrawItem;
}

3. 加载SQL数据到ListBox

在窗体Load事件中,从SQL查询数据并绑定到ListBox(以下为模拟数据,实际替换为你的SQL查询逻辑):

private void FormsProducts_Load(object sender, EventArgs e)
{
    // 模拟SQL查询结果,实际使用SqlCommand/SqlDataReader获取真实数据
    var productList = new List<Product>
    {
        new Product { Name = "A产品", MTBF = 40 },
        new Product { Name = "B产品", MTBF = 25 },
        new Product { Name = "C产品", MTBF = 0 }
    };

    listBoxProducts.DataSource = productList;
}

4. 实现自绘逻辑

在DrawItem事件中,根据每个项的MTBF值判断颜色,绘制项的背景和文本:

private void ListBoxProducts_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();

    // 避免空列表时索引越界
    if (e.Index < 0) return;

    // 获取当前项的产品数据
    var currentProduct = (Product)listBoxProducts.Items[e.Index];

    // 初始化颜色为系统默认值
    Color itemBackColor = SystemColors.Window;
    Color itemForeColor = SystemColors.WindowText;

    // 根据MTBF值设置对应颜色
    if (currentProduct.MTBF == 0)
    {
        itemBackColor = Color.Red;
        itemForeColor = Color.White; // 白色文字提升红色背景可读性
    }
    else if (currentProduct.MTBF <= 30)
    {
        itemBackColor = Color.Yellow;
    }
    // MTBF>30时使用默认颜色,无需修改

    // 绘制项背景
    using (SolidBrush bgBrush = new SolidBrush(itemBackColor))
    {
        e.Graphics.FillRectangle(bgBrush, e.Bounds);
    }

    // 绘制项文本,垂直居中对齐
    TextRenderer.DrawText(
        e.Graphics, 
        currentProduct.Name, 
        e.Font, 
        e.Bounds, 
        itemForeColor, 
        TextFormatFlags.Left | TextFormatFlags.VerticalCenter
    );

    // 绘制焦点框,保证项的交互性
    e.DrawFocusRectangle();
}

关键注意事项

  • 必须设置DrawMode = OwnerDrawFixed,否则自绘逻辑不会生效。
  • 若ListBox可能为空,需判断e.Index >= 0避免索引越界异常。
  • 从SQL获取数据时,需将查询到的产品名称和MTBF值映射到Product类的属性中。
  • 颜色可根据需求调整,比如修改背景色、前景色的RGB值。

内容的提问来源于stack exchange,提问作者ermesa.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:13:18