c# - 在绑定(bind)时更改 ListBox 的特定项目背景颜色

标签 c# winforms listbox background-color

我从事 c#.net winforms 应用程序的工作。 因为我有列表框来加载一些数据。所以我简单地从数据库中获取数据并通过相同的数据绑定(bind)列表框。为了绑定(bind)列表框,我使用了这段代码。

 try
        {
            db v = new db();
            DataTable dt = new DataTable();
            dt = v.retDataTable("select distinct(tableName),tableID from tableMaster  order by tableName ");//retDataTable is function and it return data in datatable.
            listBox1.DataSource = dt;
            listBox1.DisplayMember = "tableName";
            listBox1.ValueMember = "tableID";
        }
        catch (Exception e1)
        {
        }

现在我的问题是: 我必须检查绑定(bind)到列表框的所有数据,并根据条件更改特定项目的背景颜色。 我该怎么办?

最佳答案

您正在寻找ListBox.DrawItem Event

来自 MSDN 的示例代码:

private void ListBox1_DrawItem(object sender, 
    System.Windows.Forms.DrawItemEventArgs e)
{
    // Draw the background of the ListBox control for each item.
    e.DrawBackground();
    // Define the default color of the brush as black.
    Brush myBrush = Brushes.Black;

    // Determine the color of the brush to draw each item based  
    // on the index of the item to draw. 
    switch (e.Index)
    {
        case 0:
            myBrush = Brushes.Red;
            break;
        case 1:
            myBrush = Brushes.Orange;
            break;
        case 2:
            myBrush = Brushes.Purple;
            break;
    }

    // Draw the current item text based on the current Font  
    // and the custom brush settings.
    e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), 
        e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
    // If the ListBox has focus, draw a focus rectangle around the selected item.
    e.DrawFocusRectangle();
}

由于您有数据表作为数据源,因此您需要找到当前数据行

DataRowView drv = (DataRowView)this.listBox1.Items[e.Index];

var tableID = drv["tableID"].ToString();
var tableName =drv["tableName "].ToString();

根据tableID的数据类型,您可以将其转换为相关类型并编写条件来更改背景颜色。

您还需要使用 DrawString 方法绘制 tableName

e.Graphics.DrawString(tableName , 
            e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);

关于c# - 在绑定(bind)时更改 ListBox 的特定项目背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19353684/

相关文章:

c# - asp.net 中的替代图像显示

c# - JavaScript 正则表达式问题

c# - 旋转时调整图像大小

c# - 在 VS 2010 的 Winforms 项目中添加 WPF 窗口

c# - 从对象列表填充列表框

python - 列表框被视为Nonetype,为什么?

C# 线程和 this.Invalidate()

winforms - 如何让Windows窗体退出到系统托盘?

c# - winforms listview 不在详细 View 中显示项目

python - 相同高度的 Tkinter 列表框和复选框