以C#格式显示数据

时间:2015-08-21 18:24:52

标签: c# winforms

创建我的第一个应用程序,我在表单中显示数据时遇到了很多麻烦。目前我正在尝试使用ListBox来显示信息(有人请告诉我这个案例是否有更好的对象)。下面我发布我的数据对象,表单代码和将数据返回给我的对象的函数。 如何在Listbox中显示我的数据?

返回数据的函数

public AllChampions sendChampionRequest()
{
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create
        ("https://na.api.pvp.net//api/lol/na/v1.2/champion" + 
     ConfigurationSettings.AppSettings["ApiKey"]);
     HttpWebResponse response = (HttpWebResponse)request.GetResponse();
     Stream receiveStream = response.GetResponseStream();
     StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
     JavaScriptSerializer js = new JavaScriptSerializer();
     var champdata = readStream.ReadToEnd();
     var allChampions = (AllChampions)js.Deserialize(champdata, typeof(AllChampions));
     response.Close();
     readStream.Close();           
     return (allChampions);           
}

下面的表格代码。 Champions_Box是一个C#表单ListBox

public partial class LeagueStat : Form
{
     public LeagueStat()
     {
         InitializeComponent();
     }

     private void LeagueStat_Load(object sender, EventArgs e)
     {
          var champions = new championRequest();
          var allChampions = champions.sendChampionRequest();
          Champions_Box.DataSource = allChampions;
          Champions_Box.DisplayMember = "Champions";
     }
}

数据对象

public class AllChampions
{
    public IEnumerable<Champion> Champions { get; set; }
}
public class Champion
{
    public long Id { get; set; }
    public bool Active { get; set; }
    public bool BotEnabled { get; set; }
    public bool FreeToPlay { get; set; }
    public bool BotMmEnabled { get; set; }
    public bool RankedPlayEnabled { get; set; }
}

1 个答案:

答案 0 :(得分:2)

根据MDSN page on ListBox.DisplayMember property,您需要将DisplayMember设置为自定义对象中的某个属性。由于您当前的所有属性都不是名称字段,因此您可能需要考虑添加比Id更有用的显示内容。

因此,例如,使用如下的用户名更新您的Champion类:

public class Champion
{
    public long Id { get; set; }
    public string Username {get; set; }
    public bool Active { get; set; }
    public bool BotEnabled { get; set; }
    public bool FreeToPlay { get; set; }
    public bool BotMmEnabled { get; set; }
    public bool RankedPlayEnabled { get; set; }
}

然后以这种方式引用它(正如Bill在下面暗示的那样):

Champions_Box.DisplayMember = "Username";

对于双向数据绑定,请考虑将ListBox.ValueMember设置为您的属性之一,例如Id。

然后你就像这样使用它:

Champions_Box.ValueMember = "Id";