我有一个League.cs文件,其中包含项目的所有联赛
当我尝试在组合框上显示此数据时,它显示“App.Toolkit.Parameter”而不是联盟名称。
我将此代码用于组合:
foreach (League item in League.GetAll()) { comboBox1.Items.Add(item); }
和league.cs文件:
using System.Collections.Generic;
namespace App.Toolkit.Parameter
{
public class League : SearchParameterBase<uint>
{
public const uint BarclaysPremierLeague = 13;
public const uint Bundesliga = 19;
public const uint LigaBbva = 53;
public const uint Ligue1 = 16;
public const uint SerieA = 31;
private League(string description, uint value)
{
Description = description;
Value = value;
}
public static IEnumerable<League> GetAll()
{
yield return new League("Barclays Premier League", BarclaysPremierLeague);
yield return new League("Bundesliga", Bundesliga);
yield return new League("Liga BBVA", LigaBbva);
yield return new League("Ligue 1", Ligue1);
yield return new League("Serie A", SerieA);
}
}
}
感谢adv:)
答案 0 :(得分:3)
您可以设置ComboBox的DisplayMember
:
comboBox1.DisplayMember = "Description";
或者您可以覆盖ToString
班级中的League
:
public override string ToString()
{
return Description;
}
答案 1 :(得分:2)
你应该设置
comboBox1.DisplayMember = "Description";
comboBox1.ValueMember = "Value";
那就是说,我建议使用databindungs;
var bs = new BindingSource(League.GetAll().ToList(), null);
comboBox1.DisplayMember = "Description";
comboBox1.ValueMember = "Value";
comboBox1.DataSource = bs;
这允许你
a)使用bs.Current
来访问所选的文章
b)使用bs.MoveNext() / bs.MoveFirst()
更改选定的Leage
c)重新加载你的leages而不修改组合框,只需将bs.DatasSource设置为其他东西。
更少的代码,更少的错误,更少的头痛
private void Init()
{
var bs = new BindingSource(...);
bs.AddingNew += new AddingNewEventHandler(bs_AddingNew);
}
void bs_AddingNew(object sender, AddingNewEventArgs e)
{
string name = AskForName();
e.NewObject = CreateLeage(name);
}
现在你可以打电话
bs.AddNew();
代码中的某处。
答案 2 :(得分:1)
您可以覆盖联盟课程中的ToString方法:
public override string ToString()
{
return this.description;
}
答案 3 :(得分:0)
覆盖ToString()
方法会有所帮助。
答案 4 :(得分:0)
您已将对象添加到组合框并需要更改代码:
using System.Collections.Generic;
namespace App.Toolkit.Parameter
{
public class League : SearchParameterBase<uint>
{
public const uint BarclaysPremierLeague = 13;
public const uint Bundesliga = 19;
public const uint LigaBbva = 53;
public const uint Ligue1 = 16;
public const uint SerieA = 31;
private League(string description, uint value)
{
Description = description;
Value = value;
}
public static IEnumerable<League> GetAll()
{
yield return new League("Barclays Premier League", BarclaysPremierLeague);
yield return new League("Bundesliga", Bundesliga);
yield return new League("Liga BBVA", LigaBbva);
yield return new League("Ligue 1", Ligue1);
yield return new League("Serie A", SerieA);
}
public override string ToString()
{
return Description;
}
}
}
ovveride toString()方法。