简体   繁体   English

C# 无法将 List 绑定到 DataGridView -

[英]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.我一定要疯了 - 我似乎无法完成使用 dgv.datasource = list 代码在我的 DataGridView 中显示我的列表的简单任务。 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.我认为问题是新贡献者所说的 - DataGridView需要绑定到的属性,而不仅仅是字段。 You need Getters and Setters to get the binding to work.您需要GettersSetters才能使绑定Setters

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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