在组合框内共同传输2个数据

时间:2016-11-28 07:20:20

标签: c# wpf combobox

如何在组合框内连接2个数据?这是我的代码:

private void loadPage(object sender, RoutedEventArgs e) {
            using (var ctx = new Service()) {
                try {
                    var query1 = from prod in ctx.products select prod.brand;
                    comboBox1.ItemsSource = query1.ToList();
                    var query4 = from hosp in ctx.hospitals select hosp.name;
                    comboBox4.ItemsSource = query4.ToList();
                    var query5 = (from cont in ctx.contactPersons select new { cont.lastName, cont.firstName }).First();
                    var fName = (query5.lastName + ", " + query5.firstName);
                    comboBox5.ItemsSource = fName.ToList();
                } catch {
                    MessageBox.Show("ERROR 404: Database Not Found");
                }
            }
        }

我的模型数据是test(lastname)和test(firstname)。它有点好笑,因为它输出:

  

     

ë

     

取值

     

     

     

     

ë

     

取值

     

2 个答案:

答案 0 :(得分:2)

ItemSource expect an IEnumerable,所以你需要传递一个可枚举的。但是当你有一个字符串并且你有ToList()它时,你将它变成一个char列表。所以,你需要创建一个可枚举的并添加你想要的字符串。 例如:

comboBox5.ItemsSource = new List<String>() {fName}

或者,在您的代码示例中,只需删除&#34; First()&#34;:

var query5 = ctx.contactPersons.Select(p => p.LastName + ", " + p.FirstName).ToList();

并且您最终会得到一个可以设置为组合框的ItemSource的枚举

答案 1 :(得分:0)

这个怎么样:

 void loadPage(object sender, RoutedEventArgs e) {
            using (var ctx = new Service()) {
                try {
                    var query1 = from prod in ctx.products select prod.brand;
                    comboBox1.ItemsSource = query1.ToList();
                    var query4 = from hosp in ctx.hospitals select hosp.name;
                    comboBox4.ItemsSource = query4.ToList();
                    var query5 = (from cont in ctx.contactPersons select new { fName = cont.lastName + ", " + cont.firstName });
                    comboBox5.ItemsSource = query5.ToList();
                } catch {
                    MessageBox.Show("ERROR 404: Database Not Found");
                }
            }
        }

fName.ToList()基本上是在fName中生成单个字符的列表(在您的实例中是一个字符串)。