【问题标题】:C# Cant bind List to DataGridView -C# 无法将列表绑定到 DataGridView -
【发布时间】:2018-10-26 18:47:51
【问题描述】:

我一定快疯了 - 我似乎无法通过使用 dgv.datasource = list 代码来完成让我的列表显示在我的 DataGridView 中的简单任务。没有出现错误,但我的列表仍然是空白 - 任何人都可以帮助我确定它很明显,但我无法发现它。

    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;

        }
        }

}

这是我的课..

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

【问题讨论】:

  • 数据绑定需要属性而不仅仅是字段
  • 您能进一步解释一下吗?来自 VB 的 C# 新手
  • 它与 VB 没有什么不同——它是一个 NET 的东西

标签: c# list datagridview bind


【解决方案1】:

我认为问题在于 New Contributor 所说的 - DataGridView 需要绑定属性,而不仅仅是字段。您需要 GettersSetters 才能使绑定生效。

尝试将您的课程更改为此,它应该可以工作:

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

【讨论】:

  • 顺便说一句,如果 OP 需要只读属性,这也可以在没有 setter 的情况下工作。
  • 就是这样,谢谢伙计们 - 在我急于寻求快速解决方案时,我没有打扰使用 Get 和 Set - 懒惰花了我几个小时!
  • @Luthfay 不错的收获。不知道!
猜你喜欢
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 2018-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 2011-05-30
相关资源
最近更新 更多