首页 > 解决方案 > 级联三个组合框

问题描述

我的 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#winformscomboboxcascading

解决方案


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

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

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

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

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


推荐阅读