【问题标题】:How to link two combo boxes responsively with foreign keys如何使用外键响应地链接两个组合框
【发布时间】:2015-11-13 08:13:07
【问题描述】:

我有两张表,一张用于客户/公司,一张用于该公司的代表。我在 WCF 中编写了一个方法,我在其中加入了两个表,以便它们一起工作。应该发生的是,如果我在一个组合框中选择一个客户/公司,第二个组合框应该填充该公司的代表。

WCF

 public List<Represetative> GetRepByComp(string CompanyId)
        {
            TruckDb db = new TruckDb();
            List<Represetative> result = new List<Represetative>();

            Represetative x = new Represetative();
            Company o = new Company();

            var filter = (from reps in db.Represetatives
                          join company in db.Companies on reps.Id equals company.Id
                          where company.Id == int.Parse(CompanyId)
                          select reps);

            foreach (var item in filter)
            {
                result.Add(new Represetative()
                {
                    Id = item.Id,
                    Name = item.Name
                });
            }
            return result;
        }

WPF

private async Task LoadClient(TruckServiceClient TSC, ComboBox combobox)
        {
            List<ClientItems> clientItems = new List<ClientItems>();
            foreach (var item in await TSC.GetCompaniesAsync())
                clientItems.Add(new ClientItems { Client = item.Name });
            combobox.ItemsSource = (clientItems.ToArray());
            combobox.IsEnabled = true;
            combobox.SelectedIndex = 1;
        }

        public class ClientItems
        {
            public int Id { get; set; }

            public string Client { get; set; }

            public string RepId { get; set; }

            public override string ToString()
            {
                return Client;
            }

        }

我的问题是为代表组合框创建一个方法,以便它响应地与客户/公司组合框一起工作,有什么想法吗?

【问题讨论】:

  • ComboBox 有一个SelectionChanged 事件。在您的客户/公司组合框实例上收听此内容。在处理程序中,获取新选择的 ClientItems 实例的 RepId 并调用您的 GetRepByComp() 方法以获取 Represetative 列表以填充您的秒组合框。

标签: c# wpf wcf combobox


【解决方案1】:

正如克里斯所说,订阅 SelectionChanged 事件:

<ComboBox x:Name="comboBoxCompanies" 
      SelectionChanged="ComboBoxCompaniesSelectionChanged" />

以及后面对应的代码:

private void ComboBoxCompaniesSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Client client = e.AddedItems[0] as Client;
    if (client != null)
    {
        TruckServiceClient tsc = null; // ...
        List<Representative> representatives = GetRepByComp(tsc, client.Id.ToString());
        comboBoxRepresentatives.ItemsSource = representatives;
    }
}

问候

【讨论】:

    猜你喜欢
    • 2019-11-06
    • 2016-10-06
    • 2019-07-02
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多