【问题标题】:Initializing an object property to the value of another object property in DataGridView将对象属性初始化为 DataGridView 中另一个对象属性的值
【发布时间】:2013-06-23 15:59:25
【问题描述】:

我正在尝试将两个对象(List LedgerEntries 和 List BuyerSellers)绑定到单个 DataGridView。 LedgerEntry 包含 Buyer_Seller 的属性,我希望最终用户从 DataGridView 中的组合框(由 BuyerSellers 通用集合填充)中选择 Buyer_Seller,并将 LedgerEntries 字符串 BuyerSeller 属性设置为 Buyer_Seller 字符串 Name 属性。

目前我只使用一个 BindingSource 并且我没有定义我自己的列;它们是根据绑定到 DGV 的对象自动生成的。我有点迷茫的是如何确保一个对象中的属性被初始化为由另一个对象填充的组合框的值。提前感谢您的帮助。

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:

    在这里找到我要找的东西: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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 2013-10-28
      • 1970-01-01
      • 2016-01-12
      • 2015-10-22
      • 1970-01-01
      • 2019-01-27
      • 2020-06-22
      • 1970-01-01
      相关资源
      最近更新 更多