[英]Fill a combobox from a list from another class
所以我试图通过调用另一个类中的方法来从List
填充ComboBox
,该方法将返回List
。
public endStation()
{
InitializeComponent();
startingStation.Items.Add("Test");
Line CC = new Line();
foreach (Station station in CC.GetCC())
{
startingStation.Items.Add($"{station.Number} {station.Desc}");
}
}
public List<Station> GetCC() // Create List of CC Stations
{
var CC = new List<Station>();
int count = 0;
for (int i = 0; i < Program.file.Count; i++)
{
if (Program.file[i].Number.Contains("CC"))
{
CC.Insert(count, Program.file[i]);
count++;
}
}
return CC;
}
好吧, List<T>
没有GetCC()
但Line
有; 像这样:
private void startingStation_SelectedIndexChanged(object sender, EventArgs e) {
//TODO: you have to obtain Line instance here
Line line = new Line();
// In order to avoid constant redrawing: we want repaint combobox once,
// after all items being inserted
startingStation.BeginUpdate();
try {
// It is line (not List<T>) that provides GetCC() method
foreach (Station station in line.GetCC()) {
// String interpolation - $"..." is more readable than concatenation
startingStation.Items.Add($"{station.Number} {station.Desc}");
}
}
finally {
startingStation.EndUpdate();
}
}
编辑:您可以在Linq (专为查询而设计)的帮助下改进GetCC()
实现:
using System.Linq;
...
class Line : Station {
...
public List<Station> GetCC() {
return file
.Where(item => item.Number.Contains("CC"))
.ToList();
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.