2

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

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

现在我的问题:我 I have to check all data which i bind to listbox and change the background color of particular item as per condition. 该怎么办?

4

1 回答 1

5

您正在寻找ListBox.DrawItem 事件

来自 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您可以将其转换为相关类型并编写条件以更改背景颜色。

而且你还需要tableName通过 usingDrawString方法绘制

e.Graphics.DrawString(tableName , 
            e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
于 2013-10-14T04:57:23.073 回答