user3176656
user3176656

Reputation: 3

How to use multi combo boxes?

I am implementing a windows application in C#.Net. I have three tables: country, state, District. They all are related with foreign keys. The problem is in the District form if i select one country(combobox), the related state is not displayed in another combobox. I used selectedindexchange event for state table. But it shows

"Input String is not in a correct format"

I will give a code in below. So please help me.

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

Is there any error in the above please give me reply. Thanks.

Upvotes: 0

Views: 189

Answers (1)

Alberto Solano
Alberto Solano

Reputation: 8227

As advice, the line

if (cboCountryName.SelectedValue.ToString() != "")

could be replaced in:

if(!String.IsNullOrEmpty(cboCountryName.SelectedValue.ToString())

About your problem, from your description it isn't clear where the problem is, but I think this line is your problem:

objBEMaster.CountryId = Convert.ToInt32(cboCountryName.SelectedValue);

Instead, use the Int32.TryParse method, not to handle the exception and check if the problem is a conversion issue:

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";
}

Upvotes: 1

Related Questions