winforms 如何使其可以从“组合框”中选择值?

f1tvaqid  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(141)

我使用Windows窗体。我有一个组合框('Departments' name),它包含部门列表。通过在组合框1(Staff)中选择一个部门,将显示在该部门工作的雇员。但我无法选择雇员,因为他们没有显示
代码,填入comboBox 1(Staff). dataNames -字典(部门名称-员工数组)

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (Departaments.SelectedItem != null)
    {
        this.Staff.Items.Clear();
        var dataNames = DataForComdodox.ArrNames(Departaments.SelectedItem.ToString());
        this.Staff.Items.AddRange(dataNames);
    }
}

Form1.Designer中的程式码-comboBox 1(人员)

this.Staff.DrawMode = System.Windows.Forms.DrawMode.Normal;
this.Staff.FormattingEnabled = true;
this.Staff.Items.AddRange(new object[] {
});
this.Staff.Location = new System.Drawing.Point(374, 84);
this.Staff.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Staff.Name = "Staff";
this.Staff.Size = new System.Drawing.Size(158, 21);
this.Staff.TabIndex = 0;
this.Staff.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);

在用值填充comboBox 1(Staff)后,我试图更改Staff.SelectedIndex = 0,但最后,在选择部门时,自动选择了索引为0的雇员

lfapxunr

lfapxunr1#

如果var dataNames = DataForComdodox.ArrNames(xx)返回一个雇员类的列表或数组,则可以覆盖雇员类中的ToString()。

public class Employee  
{  
    public int EmpId { get; set; }  
    public string  EmpName { get; set; }  
    public string DeptName { get; set; }  
  
    public override string ToString()  
    {  
        return $"{this.EmpId}: {this.EmpName}";  
    }  
}

相关问题