winForms + DataGridView binding to a List

后端 未结 4 885
夕颜
夕颜 2020-12-29 20:15

I\'m trying to bind a List to a DataGridView control, and I\'m not having any luck creating custom bindings.

I have tried:

gvPr         


        
4条回答
  •  情深已故
    2020-12-29 20:39

    I can't really tell what you're trying to do with the example you included, but binding to a generic list of objects is fairly straightforward if you just want to list the objects:

        private BindingSource _gridSource;
    
        private BindingSource GridSource
        {
            get
            {
                if (_gridSource == null)
                    _gridSource = new BindingSource();
                return _gridSource;
            }
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            List list = new List();
            list.Add(new FluffyBunny { Color = "White", EarType = "Long", Name = "Stan" });
            list.Add(new FluffyBunny { Color = "Brown", EarType = "Medium", Name = "Mike" });
            list.Add(new FluffyBunny { Color = "Mottled", EarType = "Short", Name = "Torvald" });
    
            GridSource.DataSource = list;
            dataGridView1.Columns["EarType"].Visible = false; //Optionally hide a column
            dataGridView1.DataSource = GridSource;
    
        }
    

    If you only want to display specific properties of the List's type you should be able to make the unwanted column(s) invisible.

    Technically, you don't really need to create the BindingSource, but I find it's a whole lot easier when I'm doing updates or changes if I have it.

    Hope this helps.

提交回复
热议问题