在列表框中显示对象名称?

时间:2014-12-15 02:57:34

标签: c# winforms listbox

我正在尝试在列表框中显示我的对象名称,但无法以良好的方式进行。我可能会手动声明所有名称,但我想通过将对象名称显示为数据源来实现。无法找到如何做到这一点。我想知道我是否应该制作一个列表,或者是否有任何简单的方法在列表中显示我的对象名称。可能foreach循环可以轻松修复它,但我无法找到如何只选择名称并将其添加到列表框中。

我的代码如下所示:

class Platform
{

public string name, action, adventure, rpg, simulation, strategy, casual, audianceY, audianceE, audianceM;

        public Platform(string nameIn, string actionIn, string adventureIn, string rpgIn, string simulationIn, string strategyIn, string casualIn, string audianceYIn, string audianceEIn, string audianceMIn)
        {
            name = nameIn;
            action = actionIn;
            adventure = adventureIn;
            rpg = rpgIn;
            simulation = simulationIn;
            strategy = strategyIn;
            casual = casualIn;
            audianceY = audianceYIn;
            audianceM = audianceMIn;
            audianceE = audianceEIn;
        }

        public override string ToString()
        {
            return name;
        }

}



public partial class Main : Form
    {

        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load_1(object sender, EventArgs e)
        {

            //---------------------------------
            // Platform List
            //---------------------------------

            Platform PC = new Platform("PC", "++", "+++", "++", "+++", "+++", "---", "+", "++", "+++");
            Platform G64 = new Platform("G64", "++", "+++", "++", "++", "+++", "--", "+", "++", "+++");
            Platform TES = new Platform("TES", "+", "--", "+", "+", "--", "+++", "+++", "++", "---");

         }


          foreach (???)
          {
          listBox1.Items.Add(???)
          }

    }

1 个答案:

答案 0 :(得分:2)

您的代码不会按原样编译,因此我假设您打算在foreach事件中包含Main_Load循环。

如果将所有新的Platform实例添加到列表而不是单个变量,则会容易得多。然后,您可以将列表设置为DataSource,并指定显示/值成员应该是什么。

private void Main_Load(Object sender, EventArgs e)
{
    var platforms = new List<Platform> {
        new Platform("PC", "++", "+++", "++", "+++", "+++", "---", "+", "++", "+++"),
        new Platform("G64", "++", "+++", "++", "++", "+++", "--", "+", "++", "+++"),
        new Platform("TES", "+", "--", "+", "+", "--", "+++", "+++", "++", "---")
    };

    listBox1.DataSource = platforms;
    listBox1.DisplayMember = "name";
    listBox1.ValueMember = "name";
}

要绑定到“name”,您需要将其更改为属性:(或者您将获得ArgumentException

public string name { get; set; }

一些想法:

  • 如果您想重复使用这些平台,则必须在方法之外声明它们。

  • 使用getters / setter创建公共属性比你正在做的公共字段更常见,并将它们大写,如下所示:

    public string Name { get; set; }