0
Answer

DataGridView object binding problem

Iliya Iliev

Iliya Iliev

15y
3.1k
1
Hi,

I have problem with this code:

	public partial class MainForm : Form
	{
//		private List companies = new List();
		private List companies = new List(); // <============== PROBLEM !!!
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		
		void MainFormLoad(object sender, EventArgs e)
		{
			companies.Add(new Company(1, "Company 1", "Address 1", "Email 1"));
			companies.Add(new Company(2, "Company 2", "Address 2", "Email 2"));
			companies.Add(new Company(3, "Company 3", "Address 3", "Email 3"));
			companies.Add(new Company(4, "Company 4", "Address 4", "Email 4"));
			companies.Add(new Company(5, "Company 5", "Address 5", "Email 5"));

//			bindingNavigator1.BindingSource = bindingSource1;

			dataGridView1.DataSource = bindingSource1;
			dataGridView1.AutoGenerateColumns = false;
			bindingSource1.DataSource = companies;
//			bindingSource1.AllowNew = true;
			
			dataGridView1.Columns.Add("CompanyID","ID");
			dataGridView1.Columns["CompanyID"].DataPropertyName = "CompanyID";
			dataGridView1.Columns.Add("CompanyName","Name");
			dataGridView1.Columns["CompanyName"].DataPropertyName = "CompanyName";
			dataGridView1.Columns.Add("Address","Address");
			dataGridView1.Columns["Address"].DataPropertyName = "Address";
			dataGridView1.Columns.Add("EMail","E-Mail");
			dataGridView1.Columns["EMail"].DataPropertyName = "EMail";
		}
	}
	
	public class BaseCompany {}
	
	public class Company : BaseCompany
    {
        private int companyID;
        private string companyName;
        private string address;
        private string email;

        public int CompanyID
        {
            get { return companyID; }
            set { CompanyID = value; }
        }
        public string CompanyName
        {
            get { return companyName; }
            set { companyName = value; }
        }
        public string Address
        {
            get { return address; }
            set { address = value; }
        }
        public string Email
        {
            get { return email; }
            set { email = value; }
        }

        public Company()
        {
            companyID = 0;
            companyName = string.Empty;
            address = string.Empty;
            email = string.Empty;
        }
        
        public Company(int pID, string pName, string pAddress, string pEmail)
        {
            companyID = pID;
            companyName = pName;
            address = pAddress;
            email = pEmail;
        }
    }

	
When I create field "companies" as List all works fine but when I create it as List DataGridView doesn't show the data.
Why DataGridView doesn't recognize that elemants in the list are actually from type "Company" not from "BaseCompany"?