简体   繁体   English

C# 使用列表框中的数据源将 JSON 文件加载到列表框

[英]C# load JSON files to Listbox by using datasource from a listbox

I saved JSON files from a local folder.我从本地文件夹中保存了 JSON 文件。 Please see below:请看下面:

Ivan Deaking.json伊万·迪金.json

{
  "FirstName": "Ivan",
  "LastName": "Deakin",
  "Email": "ivan.deakin",
  "TeamName": "Ivan Deakin",
  "Password": "ivan12345",
  "IsActive": "Yes",
  "UserId": 5
}

And here's my code below:下面是我的代码:

private void ShowListView()
{
    //listBoxUsers.Items.Clear();
    var dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
    var outputDir = Path.Combine(dir, "Output");

    foreach (var file in Directory.GetFiles(outputDir, "*.json"))
    {
        var text = File.ReadAllText(file);

        var model = JsonConvert.DeserializeObject<UserAccount>(text);

        listBoxUsers.Items.Add(model);
    }
}

Currently, this code is using Items.Add to load the JSON file to a listview.目前,此代码使用 Items.Add 将 JSON 文件加载到列表视图。 What I am trying to achieve is to use datasource instead of Items.Add to fill the listbox.我想要实现的是使用数据源而不是 Items.Add 来填充列表框。

Please see code below:请看下面的代码:

listBoxUsers.DataSource = model;

But it doesn't allow me and it gives me an error 'Complex DataBinding accepts as a datasource either an IList or an IListSource .但它不允许我,它给了我一个错误“复杂 DataBinding 接受 IList 或 IListSource 作为数据源 I am not sure though if I need to convert the "model" first into list of strings.我不确定是否需要先将“模型”转换为字符串列表。 Can anyone help me with this?谁能帮我这个?

Your function should be like this:你的功能应该是这样的:

private void ShowListView()
{
    List<UserAccount> userAcounts = new List<UserAccount>();
    //listBoxUsers.Items.Clear();
    var dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
    var outputDir = Path.Combine(dir, "Output");

    foreach (var file in Directory.GetFiles(outputDir, "*.json"))
    {
        var text = File.ReadAllText(file);

        var model = JsonConvert.DeserializeObject<UserAccount>(text);

        userAcounts.Add(model);
    }

    listBoxUsers.DataSource = userAcounts;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM