Home > front end >  C# load JSON files to Listbox by using datasource from a listbox
C# load JSON files to Listbox by using datasource from a listbox

Time:06-07

I saved JSON files from a local folder. Please see below:

Ivan Deaking.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. What I am trying to achieve is to use datasource instead of Items.Add to fill the listbox.

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. I am not sure though if I need to convert the "model" first into list of strings. Can anyone help me with this?

CodePudding user response:

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;
}
  • Related