【问题标题】:C# winform ComboBoxC# winform 组合框
【发布时间】:2017-02-12 11:59:44
【问题描述】:

我在 C# Winform 上有一个组合框,我想用这个列表中的字符串名称变量填充它,仅此而已。这是列表代码。

class Animals
{
    public string averageMass { get; set; }
    public string lifeSpan { get; set; }
    public string whereToFind { get; set; }
    public string name { get; set; }
    public string animalImage { get; set; }
}
class Mammals:Animals
{
    public static List<Mammals> MammalList = new List<Mammals>();
    public string hairColour { get; set; }
}

【问题讨论】:

  • Google "cascading dropdownlists winform",您在表示层中有业务逻辑,将其移动到业务逻辑层并使用绑定控件或通过 SelectedValue Change 设置控件数据源来绑定 ComboBoxes事件

标签: c# winforms combobox


【解决方案1】:

您可以在 Combobox 上执行此操作:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox1.SelectedItem == "Mammals") //You can also do index e.g. comboBox1.SelectedIndex == 0
        {
            comboBox2.DataSource = mammalList;
        }
        else
        {
            comboBox2.DataSource = reptileList;
        }
    }

或者你也可以这样做:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        comboBox2.DataSource = fncGetSpecies(comboBox1.SelectedIndex);
    }

    private string[] fncGetSpecies(int intIndex)
    {
        //This will return if selected item is 0 which is Mammals or 1 if the selected item is Reptiles.
        return intIndex == 0 ? mammalList : reptileList;
    }

【讨论】:

    【解决方案2】:

    您可以根据在SelectedIndexChanged 事件处理程序中从ListBox1's 中的选择设置DataSourceListBox2,如下所示:

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(listBox1.SelectedIndex==0)//Which is Mammals list
            {
                listBox2.DataSource = reptileList;
            }
            else//Which is Reptiles list
            {
                listBox2.DataSource = mammalList;
            }
        }
    

    【讨论】:

      【解决方案3】:

      您可以使用以下代码将字符串项添加到组合框

      combobox.Items.Add(stringItem);
      

      【讨论】:

      • 一个非常模糊的答案。
      • @gplumb 这是向组合框添加数据的一般问题。你还有什么建议在这里?
      猜你喜欢
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多