我从事 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)到列表框的所有数据,并根据条件更改特定项目的背景颜色。
我该怎么办?
最佳答案
来自 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/