你这设计的有点问题吧:
档案List = new Dictionary<int, 档案Class>();
档案List.Add(档案Class.ID, 档案Class);
用了Dictionary,那之后自然是要通过 档案Class.ID 去查找对应的档案Class,但之后却没有用到;
你的需求是 从 档案List 中 筛选出符合年月等条件的记录集,列到下拉表中,然后可以在其他地方展示明细,或者编辑等操作;
常见的其实是 档案List 作为 List<档案Class>,初始时从数据库中读取所有的记录集,可以通过 sql 语句直接排好序 ;
之后当 year,month 下拉列表选择改变后,从 档案List 中提取 符合的,重新加载到 comboBox 就行了;
[C#] 纯文本查看 复制代码 /// <summary>
/// 假设 档案Class 定义如下
/// </summary>
private class 档案Class
{
public int ID { get; set; }
public string Name { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public 档案Class()
{
}
public 档案Class(int id, int year, int month)
{
ID = id;
Year = year;
Month = month;
Name = $"{id}_{year}_{month}";
}
}
// 初始化,窗体加载时
private void Init()
{
_cboYear.DropDownStyle = ComboBoxStyle.DropDownList;
_cboMonth.DropDownStyle = ComboBoxStyle.DropDownList;
_cbo档案.DropDownStyle = ComboBoxStyle.DropDownList;
_cboYear.Items.Clear();
for (int i = 2000; i < 2030; i++)
{
_cboYear.Items.Add(i);
}
_cboMonth.Items.Clear();
for (int i = 1; i <= 12; i++)
{
_cboMonth.Items.Add(i);
}
// 数据库获取所有记录
_档案List = GetAllRecord();
_cbo档案.DataSource = _档案List;
_cbo档案.DisplayMember = "Name";
_cbo档案.ValueMember = "ID";
_cboYear.SelectedIndex = 0;
_cboMonth.SelectedIndex = 0;
_cboYear.SelectedIndexChanged += cboYear_SelectedIndexChanged;
_cboMonth.SelectedIndexChanged += cboMonth_SelectedIndexChanged;
Update_档案List();
}
private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
{
Update_档案List();
}
private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
{
Update_档案List();
}
private void Update_档案List()
{
if (string.IsNullOrWhiteSpace(_cboYear.Text)) { return; }
if (string.IsNullOrWhiteSpace(_cboMonth.Text)) { return; }
int year = Convert.ToInt32(_cboYear.Text);
int month = Convert.ToInt32(_cboMonth.Text);
var list = _档案List.Where(a => a.Year == year && a.Month == month).ToList();
_cbo档案.DataSource = list;
}
private void Button1_Click(object sender, EventArgs e)
{
var obj = _cbo档案.SelectedItem as 档案Class; // 获取选择的档案
if (obj == null) { return; }
MessageBox.Show($"ID = {obj.ID }\r\nName = {obj.Name }");
} |