我正在尝试为每个类别中的项目创建一个包含类别和另一个列表框的列表框。我希望能够在第一个列表框中选择一个类别,然后第二个列表框将更改以显示该特定类别的项目。它很常见,我相信你能明白我的意思。我正在寻找它,但无法知道如何做到这一点。我已经创建了2个列表框以及我想要的值,就是这样。有什么帮助吗?
答案 0 :(得分:1)
工作示例(简化):
private class CategoryItems
{
public string Category { get; set; }
public string Item { get; set; }
public CategoryItems(string category, string item)
{
this.Category = category;
this.Item = item;
}
public override string ToString()
{
return this.Item;
}
}
private List<string> categories = new List<string>();
private List<CategoryItems> catItems = new List<CategoryItems>();
private void Form1_Load(object sender, EventArgs e)
{
categories.Add("Cat 1");
categories.Add("Cat 2");
catItems.Add(new CategoryItems("Cat 1", "Cat 1 Item 1"));
catItems.Add(new CategoryItems("Cat 1", "Cat 1 Item 2"));
catItems.Add(new CategoryItems("Cat 2", "Cat 2 Item 1"));
catItems.Add(new CategoryItems("Cat 2", "Cat 2 Item 2"));
foreach (string cat in categories)
{
listBox1.Items.Add(cat);
}
listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox2.Items.Clear();
foreach (CategoryItems ci in catItems)
{
if (ci.Category == listBox1.SelectedItem.ToString())
listBox2.Items.Add(ci);
}
}
答案 1 :(得分:1)
我创建了一个带有两个列表框listbox1和listbox2的winform,这就是我的Form1.cs看起来像
namespace WinFormsApp
{
public partial class Form1 : Form
{
private List<Category> categories;
public Form1()
{
InitializeComponent();
categories = new List<Category>();
var categoryOne = new Category { Name = "Category 1"} ;
categoryOne.Items.Add( new CategoryItem { Name = "Item 1"} );
var categoryTwo = new Category { Name = "Category 2" };
categoryTwo.Items.Add( new CategoryItem { Name = "Item 2" } );
categories.Add( categoryOne );
categories.Add( categoryTwo );
}
private void Form1_Load(object sender, System.EventArgs e)
{
categoryBindingSource.DataSource = categories;
}
}
public class Category
{
public string Name { get; set; }
public List<CategoryItem> Items { get; private set; }
public Category()
{
Items = new List<CategoryItem>();
}
}
public class CategoryItem
{
public string Name { get; set; }
}
}
这是InitializeComponent()代码
this.listBox1.DataSource = this.categoryBindingSource;
this.listBox1.DisplayMember = "Name";
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(24, 24);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(242, 238);
this.listBox1.TabIndex = 0;
this.listBox1.ValueMember = "Items";
this.categoryBindingSource.DataSource = typeof(Category);
this.listBox2.DataSource = this.itemsBindingSource;
this.listBox2.FormattingEnabled = true;
this.listBox2.Location = new System.Drawing.Point(286, 24);
this.listBox2.Name = "listBox2";
this.listBox2.Size = new System.Drawing.Size(276, 238);
this.listBox2.TabIndex = 1;
this.listBox2.ValueMember = "Name";
this.itemsBindingSource.DataMember = "Items";
this.itemsBindingSource.DataSource = this.categoryBindingSource;
答案 2 :(得分:0)