【问题标题】:Cascading three ComboBoxes级联三个组合框
【发布时间】:2018-11-06 13:38:26
【问题描述】:

我的 Windows 窗体有三个组合框。 CmdCountry 引用 CmdContinent 的子表,CmdCity 引用 CmdCountry 的子表。

但是当我尝试通过编码从 cmbContinent_SelectedIndexChanged 获取 ContinentId 时,出现“格式错误”之类的错误。

int ContId = Convert.Into32(cmbContinent.SelectedValue.ToString());

我的前两个组合框如下:

private void Continent()
{
    var continent = (from u in db.Continent
                     select new { u.ContinentName,  u.ContinentId }
                    ).ToList();
    cmbContinent.DataSource = continent;
    cmbContinent.DisplayMember = "ContinentName";
    cmbContinent.ValueMember = "ContinentId";
}

private void cmbContinent_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cmbContinent.SelectedValue.ToString() != null)
    { 
        int ContId = Convert.Into32(cmbContinent.SelectedValue.ToString()); // Here I get the error
        var country = (from u in db.Country
                       where u.ContinentId == ContId
                       select new { u.CountryId, u.CountryName }).ToList();

        cmbCountry.DataSource = country;
        cmbCountry.DisplayMember = "CountryName";
        cmbCountry.ValueMember = "CountryId";
    }
}

并在构造函数中加载第一个组合框大陆:

public NewAccount()
{
    InitializeComponent(); 
    Continent();
}

如果有人可以提供帮助,我将不胜感激。

【问题讨论】:

    标签: c# winforms combobox cascading


    【解决方案1】:

    我在我当前的项目中使用了一个 ComboBox,并且我做了类似的事情。

    int valueMax = Convert.ToInt32(cbxNumberValues.SelectedItem);
    

    对于您的代码,这里应该可以工作。请注意,我几乎没有做任何修改以更常规地编码。

    int contId = Convert.ToInt32(cmbContinent.SelectedItem);
    

    我还建议使用“cbx”或“cmb”而不是“cmd”,因为它通常会说命令。但这不是很重要

    【讨论】:

    • 我认为cmd 是问题中的错字,因为代码确实使用了cmb。我个人(嗯,曾经)是一个cbo 的家伙:)
    • @Toucanite 谢谢你的回复,我不知道为什么,但现在它就像我从一开始所做的那样工作 intcontinentId = Convert.ToInt32(cmbContinent.SelectedValue.ToString());跨度>
    • @HelenTekie 如果您原始帖子中的错字出现在代码中,它可能会解释它。
    • @Toucanite 抱歉,现在我的第三个组合框遇到了同样的问题。很奇怪......我得到同样的错误
    • @HelenTekie 很高兴听到这个消息,希望对您有所帮助。祝你的项目好运。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多