简体   繁体   中英

Winforms combobox displaying class names instead of actual object name

I have this class that contains a static list

public class TypeList
{
    public string Name;
    public string NameTag;

    public TypeList(string Name, string NameTag)
    {
        this.Name = Name;
        this.NameTag = NameTag;
    }

    public static List<TypeList> DataType = new List<TypeList>() {
        new TypeList("DataType","-1"),
        new TypeList("OpOne","1"),
        new TypeList("OpTwo","2"),
    };
}

I then put the static list called DataType into a combobox:

public void RefreshList()
{
    List<TypeList> data = new List<TypeList>();
    data = TypeList.DataType;

    typeCB.DataSource = data;
    typeCB.DisplayMember = "Name";
    typeCB.ValueMember = "NameTag";
    typeCB.SelectedValue = -1;
    typeCB.SelectedText = "Select DataType";
}

However, when I run it, all I get are the classnames in my combobox. Is something wrong with my code? I tried to do

data.Select(x=>x.Name).ToList()

But that just gives me the name portion.

I might be wrong, but based on the Documentation and Example it might be that this Feature only works with public property getters, not public fields:

Gets or sets the property to display for this ListControl.

public class USState
{
    private string myShortName;
    private string myLongName;

    public USState(string strLongName, string strShortName)
    {

        this.myShortName = strShortName;
        this.myLongName = strLongName;
    }

    public string ShortName
    {
        get
        {
            return myShortName;
        }
    }

    public string LongName
    {

        get
        {
            return myLongName;
        }
    }

}

Of course I would also advise against making the list a part of the Type class. A simple Programm scope static would be better. If that is the case and as autoproties have have become a thing by now, this should be enough of a fix:

public class Type
{
public string Name { private set; get } ;
public string NameTag {private set; get };

    public TypeList(string Name, string NameTag)
    {
        this.Name = Name;
        this.NameTag = NameTag;
    }

}



//use in the class of main, the form or some similar central point
static List<Type> TypeList = new List<Type>();

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