2016-05-07 56 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值保存在表中。對不起,佔用你的時間:) –