2013-06-23 202 views
2

我試圖將兩個對象(List LedgerEntries和List BuyerSellers)綁定到單個DataGridView。 LedgerEntry包含Buyer_Seller屬性,我希望最終用戶從DataGridView中的組合框(由BuyerSellers泛型集合填充)中選擇Buyer_Seller,並將LedgerEntries字符串BuyerSeller屬性設置爲Buyer_Seller字符串Name屬性。將對象屬性初始化爲DataGridView中另一個對象屬性的值

目前我只使用一個BindingSource,我沒有定義自己的列;它們是基於綁定到DGV的對象自動生成的。我有點失落的地方是如何確保一個對象中的屬性被初始化爲由另一個對象填充的組合框的值。預先感謝您的幫助。

回答

0

找到了我一直在尋找在這裏:http://social.msdn.microsoft.com/Forums/vstudio/en-US/62ddde6c-ed96-4696-a5d4-ef52e32ccbf7/binding-of-datagridviewcomboboxcolumn-when-using-object-binding

public partial class Form1 : Form 
{ 
    List<LedgerEntry> ledgerEntries = new List<LedgerEntry>(); 
    List<Address> addresses = new List<Address>(); 
    BindingSource entrySource = new BindingSource(); 
    BindingSource adSource = new BindingSource(); 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     entrySource.DataSource = ledgerEntries; 
     adSource.DataSource = addresses; 

     DataGridViewComboBoxColumn adr = new DataGridViewComboBoxColumn(); 
     adr.DataPropertyName = "Address"; 
     adr.DataSource = adSource; 
     adr.DisplayMember = "OrganizationName"; 
     adr.HeaderText = "Organization"; 
     adr.ValueMember = "Ref"; 

     ledger.Columns.Add(adr); 
     ledger.DataSource = entrySource; 

     addresses.Add(new Address("Test1", "1234", 5678)); 
     addresses.Add(new Address("Test2", "2345", 9876)); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     foreach (LedgerEntry le in ledgerEntries) 
      MessageBox.Show(le.Address.OrganizationName + " // " + le.Description); 
    } 
} 

public class LedgerEntry 
{ 
    public string Description { get; set; } 
    public Address Address { get; set; } 
} 

public class Address 
{ 
    public string OrganizationName { get; set; } 
    public string StreetAddress { get; set; } 
    public int ZipCode { get; set; } 

    public Address(string orgname, string addr, int zip) 
    { 
     OrganizationName = orgname; 
     StreetAddress = addr; 
     ZipCode = zip; 
    } 

    public Address Ref 
    { 
     get { return this; } 
     set { Ref = value; } 
    } 

    public override string ToString() 
    { 
     return this.OrganizationName; 
    } 
} 
相關問題