[英]Showing object names in a 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(???)
}
}
您的代碼不會按原樣編譯,因此我僅假設您打算在Main_Load
事件中包含foreach
循環。
如果將所有新的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";
}
要綁定到“名稱”,您需要將其更改為屬性:(否則您將獲得ArgumentException
)
public string name { get; set; }
一些想法:
如果要重用這些平台,則必須在方法之外聲明它們。
與您當前正在使用的公共字段相比,使用getter / setter創建公共屬性要更典型,並且也要大寫它們,如下所示:
public string Name { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.