简体   繁体   中英

C# Cant bind List to DataGridView -

I must be going mad - I can't seem to do the simple task of making my list display in my DataGridView by using the dgv.datasource = list code. No errors appear but my list remains blank - can anyone help i'm sure its something obvious but I just can't spot it.

    namespace WindowsFormsApp4
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<DGVNames> NamesList = new List<DGVNames>();

            NamesList.Add(new DGVNames("Adam", 18, "Wigan"));
            NamesList.Add(new DGVNames("Bob", 21, "Bolton"));

            dataGridView1.AutoGenerateColumns = true;

            dataGridView1.DataSource = NamesList;

        }
        }

}

and this is my class..

namespace WindowsFormsApp4
{
    class DGVNames
    {
        public String strName;
        public int intAge;
        public String strTown;

        public DGVNames(String _strName, int _intAge, String _strTown)
        {
            strName = _strName;
            intAge = _intAge;
            strTown = _strTown;
        }
    }
}

I think the issue is what New Contributor said - DataGridView requires properties to bind to, not just fields. You need Getters and Setters to get the binding to work.

Try this changing your class to this and it should work:

public String strName { get; set; }
public int intAge { get; set; }
public String strTown { get; set; }

public DGVNames(String _strName, int _intAge, String _strTown)
{
    strName = _strName;
    intAge = _intAge;
    strTown = _strTown;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM