“myObject的'不包含名为'ID'(不是笔误)的属性 [英] 'myObject' does not contain a property with the name 'ID' (Not a typo)

查看:201
本文介绍了“myObject的'不包含名为'ID'(不是笔误)的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个ASP.NET C#网站,我有一个DropDownList,我结合我所创建的对象的列表。结合DropDownList中的code是这样的:

I am building an ASP.NET C# website, and I have a dropdownlist that I am binding to a list of objects that I have created. The code that binds the dropdownlist looks like this:

protected void PopulateDropdownWithObjects(DropDownList dropdownlist, List<myObject>() myObjects)
{
    dropdownlist.DataValueField = "ID";
    dropdownlist.DataTextField = "Name";
    dropdownlist.DataSource = myObjects;  // my code fails here
    dropdownlist.DataBind();
}

然而,当它击中的方法中的3号线,则将引发异常:

However, when it hits the 3rd line within the method, an exception is thrown:

DataBinding: 'myObject' does not contain a property with the name 'ID'.

不过,我可以清楚地看到myObject.ID价值,同时我调试:我可以在即时窗口中访问它,它是公开的,它不是空的,我拼写正确,并用正确的情况:

However, I can clearly see the myObject.ID value while I debug: I can access it in the Immediate window, it's public, it isn't null, and I spelled it correctly and with the proper case:

public class myObject
{
    public int ID;   // see? "ID" is right here!
    public string Name;

    public myObject(
        int id,
        string name
        )
    {
        this.ID = id;
        this.Name = name;
    }
}

还有什么可以引起这个错误?

Is there anything else that can cause this error?

推荐答案

您code就不行,因为 ID 是的字段,不是的属性

Your code will not work, because ID is a field, not a property.

如果你改变你的类,如下图所示,在code将工作打算:

If you change your class, as shown below, the code will work as intended:

public class myObject
{
    public int ID    // this is now a property
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }

    public myObject(
        int id,
        string name
        )
    {
        this.ID = id;
        this.Name = name;
    }
}

这篇关于“myObject的'不包含名为'ID'(不是笔误)的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆