2016-05-07 55 views
2

组合框的值应显示在文本框中。 有一个表格,其中属性“name”显示在组合框中。在文本框中选择的值的基础上应该导出该值的属性“价格”。数据库通过一个模型ADO.NET连接。 我认为CHANNEL类型的“ConnectionString = @”Data Source = ....“是没有必要的,因为我已经连接了数据库,一切正常,一切都保存并更改了。唯一剩下的就是这个结论我希望在文本框中使用值,我是C#的新手,为我的问题回顾了一些经验教训,他们总是使用这个连接字符串,我不需要它。对不起你是误会了。组合框的值应显示在文本框中

namespace test6 
    { 
     public partial class Form5 : Form 
     { 
     centrEntities db; 
     public Form5() 
    { 

     InitializeComponent(); 
     FillCombobox(); 

    } 

     private void Form5_Load(object sender, EventArgs e) 
    { 

     db = new centrEntities(); 
     db.Configuration.ProxyCreationEnabled = false; 
     db.Configuration.LazyLoadingEnabled = false; 
     orderBindingSource.DataSource = db.order.ToList(); 

    } 

    private void FillCombobox() 
    { 
     using (centrEntities c = new centrEntities()) 
     { 

      comboService.DataSource = c.service.ToList(); 
      comboService.ValueMember = "serviceID"; 
      comboService.DisplayMember = "name"; 


     } 
    } 

Table - values

how it looks.

回答

1

我已经在你的代码中的事件SelectedIndexChanged添加到ComboBoxcomboService这样的:

public partial class Form5 : Form 
{ 
    centrEntities db; 
    public Form5() 
    { 
     InitializeComponent(); 
     FillCombobox(); 
     comboService.SelectedIndexChanged += new EventHandler(comboService_SelectedIndexChanged); 
    } 

    private void Form5_Load(object sender, EventArgs e) 
    { 
     db = new centrEntities(); 
     db.Configuration.ProxyCreationEnabled = false; 
     db.Configuration.LazyLoadingEnabled = false; 
     orderBindingSource.DataSource = db.order.ToList(); 
    } 

    private void FillCombobox() 
    { 
     using (centrEntities c = new centrEntities()) 
     { 
      comboService.DataSource = c.service.ToList(); 
      comboService.ValueMember = "serviceID"; 
      comboService.DisplayMember = "name"; 
     } 
    } 

    private void comboService_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     if (comboService.SelectedValue != null) 
     { 
      using (centrEntities c = new centrEntities()) 
      { 
       var price = (from serv in c.service 
          where serv.serviceID == Convert.ToInt32(comboService.SelectedValue) 
          select serv.price).SingleOrDefault(); 

       TextPriceName.Text = price.ToString(); 
      } 
     } 
    } 
} 
+0

感谢花花公子。做得好。真实文本框显示不是“价格”和“服务ID”。 –

+0

在'comboService.ValueMember =“price”'中按价格更改serviceId; –

+0

哦,是的。我没注意到。 但问题解决了一半。事实是,当您从组合框中选择一个值时,在文本框中显示相应的值,谢谢。但是转换到下一个文本框后,我使用的最后两个字段(组合框,文本框)中的数据不会保存,而是保持空白。所以它应该是原则上的。因为通过comboService.ValueMember =“serviceID”,我们将所选服务按顺序维护到表中。你建议继续保持“价格”,尽管这个值不能用int值保存在表中。对不起,占用你的时间:) –