2015-09-14 14 views
1

爲了開始,我試圖瞭解DataGridView/BindingSource/DataRelation等。我已經閱讀了一些教程並收集了有關該主題的信息。到目前爲止,我認爲我理解了基礎知識,現在我正在試驗我學到的東西。基於來自第三個表的信息的主要細節關係

到目前爲止我的代碼從本教程播放: https://msdn.microsoft.com/en-us/library/c12c1kx4%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

在我的項目有3個表:

Table A  
    A_id eng_word 
    0   dog 
    1   cat 

Table B 
    B_id ger_word 
    0  Hund 
    1  Katze 
    2  Maus 

Table C (Relation) 
    A_id B_id 
    0  0 
    0  1 
    1  1 
    1  2 

目標是擁有DataGridViews每個表A和表B與BindingSource和DataRelations,因此,當我點擊DataGridView A的一個條目時,顯示了表B中的所有元素,這些元素可能是根據表C的翻譯。

 DataRelation relation = new DataRelation("Relation", 
      data.Tables["tableA"].Columns["A_id"], 
       data.Tables["tableB"].Columns["B_id"]); 
     data.Relations.Add(relation); 

     bindingSourceA.DataSource = data; 
     bindingSourceA.DataMember = "tableA"; 

     bindingSourceB.DataSource = bindingSourceA; 
     bindingSourceB.DataMember = "Relation"; 

這顯然是不工作,而不必調用表B的表C連接,但我認爲它可能與DataRelation和BindingSource做。從表A到表C的關係不是問題,但對錶B而言,我認爲不可能。

實現我的目標有沒有什麼進展,或者這樣做只是錯誤?任何意見或指針在正確的方向將非常感激。

+0

我不認爲你可以做到這一點,沒有加入B和C.如果你加入他們到data.Tables [「tableB」]那麼你在那裏,或者我錯過了什麼? – GuidoG

+0

我正在使用SqlDataAdapter來選擇數據,當它們匹配時,我想更新表。我不認爲這將是可能了,如果我會採取加入辦法。 另外我不確定如果這是一個很好的做法,如果B和C是巨大的,生產一個更大的連接表。 – Urknecht

+0

您可以爲您的適配器設置自己的更新語句,以便更新已連接的表格不成問題。我通常在sql server中創建一個視圖來加入表格。當選擇我然後使用「從myView選擇*」和更新時,我使用「select * from myTable」作爲命令。完美適合我。 – GuidoG

回答

0

根據要求提供了一個如何影響命令構建器的示例,因此它構建了myTable的更新,而不是myView或聯接表。
變量表格是填充了「select * from myView」或「select Bfield1,C.field2 from B join C on ...」的實際DataTable
請確保myTable中的每個字段都存在在myView

using (SqlConnection connection = new SqlConnection(_ConnectionString)) 
{ 
    connection.Open(); 
    using (SqlDataAdapter adapter = new SqlDataAdapter()) 
    { 
     using (SqlCommand command = new SqlCommand()) 
     { 
      using (SqlCommandBuilder builder = new SqlCommandBuilder()) 
      { 
       adapter.SelectCommand = command;// Command; 
       adapter.SelectCommand.Connection = connection; 
       builder.DataAdapter = adapter; 

       // here I let the command builder think that the table is myTable in stead of myView 
       adapter.SelectCommand.CommandText = "select * from myTable"; 
       adapter.UpdateCommand = builder.GetUpdateCommand(true).Clone(); 
       adapter.DeleteCommand = builder.GetDeleteCommand(true).Clone(); 

       adapter.Update(Table); 
      } 
     } 
    } 
} 
+0

謝謝你的代碼和堅持。最後我得到了一切工作。 – Urknecht