简体   繁体   English

我该怎么做才能选择“组合框”中的值?

[英]How do I make it so that the values from the 'combobox' can be selected?

I work in Windows Forms. I have a combobox ('Departments' name) it contains a list of departments.我在 Windows Forms 工作。我有一个 combobox(“部门”名称),它包含一个部门列表。 By selecting a department in comboBox1(Staff), employees working in this department appear.通过在 comboBox1(Staff) 中选择一个部门,将出现在该部门工作的员工。 But I can't select an employee, because they are not displayed但我不能 select 一个员工,因为他们没有显示

Code, filling in comboBox1(Staff).代码,填写comboBox1(Staff)。 dataNames - dictionary(department name - array of employees) 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);
    }
}

Code in Form1.Designer - comboBox1(Staff) Form1.Designer 中的代码 - comboBox1(Staff)

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);

I tried to change Staff.SelectedIndex = 0, after I fill comboBox1(Staff) with values, but in the end, when choosing a department, an employee was selected automatically with an index of 0在用值填充 comboBox1(Staff) 之后,我尝试更改 Staff.SelectedIndex = 0,但最后,在选择部门时,自动选择了索引为 0 的员工

If var dataNames = DataForComdodox.ArrNames(xx) returns a list or array of class employees, you could override the ToString() in the employee class.如果 var dataNames = DataForComdodox.ArrNames(xx) 返回 class 名员工的列表或数组,您可以覆盖员工 class 中的 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}";  
    }  
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM