Jonathan Escobedo
Jonathan Escobedo

Reputation: 4053

LINQ and ComboBox DataSource issue

How far is the code for best functionallity? I have two ComboBox, so the first is related for choose the company, and the second for choose the branch-office in relation with the one.

I note that the only way I can fill datasource with filtering .Where on LINQ is on this way, maybe Im wrong please take a moment for look the following snippet :

private void cboCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            var _index = ((ComboBox)sender).SelectedIndex;
            using (DB db = new DB())
            {
                var su = (from s in db.Branchs select s);

                if (cboCompany.SelectedIndex == 0)
                {
                    cboBranch.DataSource = su.Where(x => x.codeCompany == 1).Select(x => x.name).ToList();
                }
                else if (cboCompany.SelectedIndex == 1)
                {
                    cboBranch.DataSource = su.Where(x => x.codeCompany == 2).Select(x => x.name).ToList();
                }

                cboBranch.BindingContext = this.BindingContext;
                cboBranch.DisplayMember = "name";
                cboBranch.SelectedIndex = 0;
            }
        }

Thanks in Advance!

Upvotes: 0

Views: 2604

Answers (1)

Pavel Minaev
Pavel Minaev

Reputation: 101565

Rather than hand-coding this, I would make data binding do all this work for me. In particular, it can be set up thus:

  • Make it so that your Company class has a property to get all associated branches - e.g. Company.Branches. If you use LINQ to SQL or Entity Framework, there should be one there already.
  • Have two BindingSources, bsCompanies and bsBranches.
  • Set cboCompany.DataSource to bsCompanies, and cboBranch.DataSource to bsBranches
  • Set bsCompanies.DataSource to collection/DataSet that contains companies.
  • Set bsBranches.DataSource to Branches under bsCompanies (the form designer should let you do this after you do the previous step, if your collection is strongly typed).

Now whenever user picks a different company in the first combo, the current item in the companies binding source will change. This will cause binding for the second binding source to re-evaluate, and set list of branches for a newly selected company to be the source for the second combo.

Upvotes: 2

Related Questions