我在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.
我该怎么办?
答案 0 :(得分:5)
来自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
方法
DrawString
e.Graphics.DrawString(tableName ,
e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);