Child Cobobox Return Null if DataValue Combobox NotExist in Child table ( LINQ )

Viewed 58

information

i have 3 table

tblCountry

enter image description here

tblStateName

enter image description here

tblState

enter image description here

tblState Child of tblStateName (StateName_ID) ( For Better Handle )

tblState Child of tblCountry (Country_ID) ( Cascade all Know This )

i create 1 form with 2 combobox

enter image description here

i use this code for load 2 combobox DataValue

    private void Form01_Load(object sender, EventArgs e)
    {
        //Load CountryComboBox Source from Table01
        using (UnitOfWork db = new UnitOfWork())
        {
            // At first assign properties DisplayMember and ValueMember.
            cmbCountry.DisplayMember = "Country";
            cmbCountry.ValueMember = "Country_ID";

            // And then assign DataSource property of the CountryComboBox .
            cmbCountry.DataSource = db.CountryRepository.Get();
        }
    }

    //Load StateComboBox From Table02
    private void cmbCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectedValue = cmbCountry.SelectedValue.ToString();

        using (UnitOfWork db = new UnitOfWork())
            if (!string.IsNullOrEmpty(selectedValue))
            {
                // At first assign properties DisplayMember and ValueMember.
                cmbState.DisplayMember = "StateName";
                cmbState.ValueMember = "State_ID";
                // And then assign DataSource property of the cmbState.
                var result = (from state in db.StateRepository.GetNameIDByFilter(selectedValue)
                                              join stateName in db.StateNameRepository.Get() on state.StateName_ID equals stateName.Statename_ID

                                              select new
                                              {
                                                  State_ID = state.State_ID,
                                                  StateName = stateName.StateName
                                              }).ToList();

                cmbState.DataSource = result;
            }

after load form i see this result

enter image description here

if i Select Country01, i see 4 Result in cmbState ( Its Well and Work Fine )

enter image description here

MyProblem

but if i Select 'Country02' ( this Value not child in tblState ) but i see First Value From tblState like this

enter image description here

What I need ?

how i can select Country02 and See Null in cmbState ? or better ( Return Null If Country_ID not Exist in State table ) and cmbState is Null

( SRY For My bad English )

1 Answers

You should clear cmbState after reloding data, if the result is null or empty, like the following code :

if(result == null || result.Count == 0)
{
 cmbState.DataSource = null;
 cmbState.DataBindings.Clear();
}else
{
 cmbState.DataSource = result;
}

I hope you find this helpful.

Related