在c#表单中显示数据

本文关键字:显示 数据 表单 | 更新日期: 2023-09-27 18:09:13

创建我的第一个应用程序时,我在表单中显示数据时遇到了很多麻烦。目前我正试图使用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; }
}

在c#表单中显示数据

根据ListBox上的MDSN页面。属性,您需要将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。

那么你可以这样使用:

Champions_Box.ValueMember = "Id";