2012-06-06 112 views
0

我有一個DataSet,我想要可視化和使用。我使用DataGridView組件來顯示它的表格,但是當涉及到添加新行/編輯現有行時,我不想使用DataGridView的功能:我想用TextBoxes和ComboBoxes來顯示自定義窗體,和確定/取消按鈕。有一個名稱(字符串),格式(字符串),圖像(字節[]),Attr1(字符串),Attr2(字符串),IsSpecial(布爾)列的表格。 Forme和Attr2可以爲空,其他則不可以,Image應該包含一張圖片。此外,Attr1和Attr2必須從另一個表(具有ID(long),Name(string)列)中查找。使用自定義表單編輯DataRows

因此,我創建一個新窗體,放置兩個文本框,一個picturebox,兩個combobox和一個複選框。我已經有一個問題:如何在文本框/組合框中表示DBNull?

接下來是綁定本身。我認爲我必須這樣做:

class MainForm 
{ 
    // ... 
    private void btAdd_Click(object sender, EventArgs e) 
    { 
     using (EditFrom editForm = new EditForm()) 
     { 
      // I have to create a new row, right? 
      var newRow = theTable.newStrongTypedRow(); 

      if (editForm.ShowData(binding) == DialogResult.OK) 
       theTable.addStrongTypedRow(newRow); 
     } 
    } 

    private void btEdit_Click(object sender, EventArgs e) 
    { 
     using (EditFrom editForm = new EditForm()) 
     { 
      if (editForm.ShowData(binding) == DialogResult.OK) 
       binding.EndEdit(); 
      else 
       binding.CancelEdit(); 
     } 
    } 
} 

class EditForm 
{ 
    // ... 
    public DialogResult ShowData(SomeBinding binding) 
    { 
     // tie the controls to the datarow which is being edited right now 
     BindAllControls(binding); 

     // let the user input the data 
     return ShowDialog(); 
    } 
} 

但是,我用什麼「SomeBinding」? BindAllControls()裏面應該是什麼?或者,也許我有這個顛倒,這不是我應該如何表示/編輯數據?也許有人可以提出一本關於這個話題的書?

回答

0

我想你會想用BindingSource來處理你所有的綁定。 您可以將控件配置爲綁定到BindingSource,並且它應該處理控件和DataSet之間的所有轉換。

綁定可以像這樣設置: this.nameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.testDataBindingSource, "Name", true)); 您可以將BindingSource作爲「SomeBinding」傳入。

+0

那麼,這很整潔,但查找呢?我必須將組合框與一個補充表綁定......將它與mainTableBindingSource一起傳遞也是合理的?那麼我可以爲它構造兩個新的BindingSource ......但是,也許我應該傳遞的是某種DataView?你看,我正在編寫一個小應用程序,但我也想學習一些東西,所以我想像「大個子」那樣做。 –

+0

我有一些使用數據綁定的大型WinForms應用程序,它非常適用。如果可以,我嘗試不使用DataSets,而是綁定到我的模型(對象)。我會建議尋找這種方法。請查看[http://www.dnrtv.com/default.aspx?showNum=7](http://www.dnrtv.com/default.aspx?showNum=7)。它有點古老,但仍然很有價值。 –

+0

使用對象綁定可以簡單地傳遞一個類實例,而不是一些抽象的數據結構。我發現它也產生了更清晰和可理解的代碼。 –