[英]C# Winforms ListBox Set BackColor when item meets condition
I have a collection that is the DataSource of a ListBox. 我有一个集合,它是ListBox的DataSource。 I'd like to enumerate the ListBox items and change the BackColor when the collection item has a certain property.
我想枚举ListBox项并在集合项具有特定属性时更改BackColor。 The code in the for isn't working at all and i'm lost.
for中的代码根本不起作用,我迷路了。 How would i change the BackColor is the corresponding Categorie has a certain ID ?
我如何更改BackColor是相应的Categorie有一定的ID?
categorien.Add(new Categorie() { ID = 0, Naam = "Blond" });
categorien.Add(new Categorie() { ID = 1, Naam = "Donker" });
listBox1.DataSource = categorien;
listBox1.DisplayMember = "Naam";
listBox1.ValueMember = "ID";
for (int i = 0; i < listBox1.Items.Count; i++ ) {
if (categorien.ID == someID) {
listBox1.Items[i].BackColor = Color.Gray;
}
}
try below 试试下面
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
var category = listBox1.Items[e.Index] as Categorie;
Color backColor = Color.Green;
if (category.ID == someID)
{
backColor = Color.Gray;
}
// draw back color and text
}
It's a bit more work to color specific items in a listbox. 为列表框中的特定项目着色要多做一些工作。 See the discussion below.
请参阅下面的讨论。
Background color of a ListBox item (winforms) ListBox项的背景颜色(winforms)
Thanks to the suggestion of Damith (please upvote him) here the sollution, i publish the methods that gets executed when the user clicks the dataGridView with products, the corresponding categories then are selected in the listbox. 感谢Damith的建议(请点赞他)这里的sollution,我发布了当用户点击带产品的dataGridView时执行的方法,然后在列表框中选择相应的类别。
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e) {
listBox1.ClearSelected();
if (dataGridView1.SelectedRows.Count == 1){
List<CatProd> catProdLijst = catprod.Where(c => c.ProdID ==
(int)dataGridView1.SelectedRows[0].Cells["ID"].Value).ToList();
foreach (CatProd cp in catProdLijst) {
for (int i = 0; i < listBox1.Items.Count; i++) {
var category = listBox1.Items[i] as Categorie;
if (category.ID == cp.CatID) {
listBox1.SetSelected(i, true);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.