我正在C#.Net
中实现一个Windows应用程序。我有三张桌子:国家,州,区。它们都与外键有关。
问题是在区域形式如果我选择一个国家(组合框),相关状态不会显示在另一个组合框中。我将selectedindexchange
事件用于状态表。但它显示
“输入字符串的格式不正确”
我将在下面给出一个代码。所以请帮助我。
private void DistrictMaster_Load(object sender, EventArgs e)
{
BEMaster objBEMaster = new BEMaster();
BLMaster objBLMaster = new BLMaster();
cboCountryName.DataSource = objBLMaster.GetCountry();
cboCountryName.ValueMember = "CountryId";
cboCountryName.DisplayMember = "CountryName";
}
private void cboCountryName_SelectedIndexChanged_1(object sender, EventArgs e)
{
try
{
if (cboCountryName.SelectedValue.ToString() != "")
{
BEMaster objBEMaster = new BEMaster();
objBEMaster.CountryId = Convert.ToInt32(cboCountryName.SelectedValue);
BLMaster objBLMaster = new BLMaster();
cboStateName.DataSource = objBLMaster.GetStateByCountryId(objBEMaster);
cboStateName.DisplayMember = "StateName";
cboStateName.ValueMember = "StateId";
}
}
catch (Exception)
{
throw;
}
}
以上是否有任何错误请给我回复。 感谢。
答案 0 :(得分:1)
作为建议,行
if (cboCountryName.SelectedValue.ToString() != "")
可以替换为:
if(!String.IsNullOrEmpty(cboCountryName.SelectedValue.ToString())
关于您的问题,根据您的说明,我们不清楚问题所在,但我认为这一行是您的问题:
objBEMaster.CountryId = Convert.ToInt32(cboCountryName.SelectedValue);
相反,请使用Int32.TryParse方法,而不是处理异常并检查问题是否是转换问题:
int myCountry;
bool result = Int32.TryParse(cboCountryName.SelectedValue, out myCountry);
if(result)
{
BEMaster objBEMaster = new BEMaster();
objBEMaster.CountryId = myCountry;
BLMaster objBLMaster = new BLMaster();
cboStateName.DataSource = objBLMaster.GetStateByCountryId(objBEMaster);
cboStateName.DisplayMember = "StateName";
cboStateName.ValueMember = "StateId";
}