Search code examples
c#datagridviewwindows-forms-designerlitedb

How to display LiteDB data in DataGridView?


I am new to LiteDB, however it seems perfect for my application after using a cumbersome CSV file, but I am having trouble displaying the data in a Windows Form DataGridView.

My LiteDB database is working fine with storing data but need help displaying the data.

Here is my POCO and user data store method:

public class Preset
{
   [BsonId]
   public int _id { get; set; }
   public string Name { get; set; }
   public int X { get; set; }
   public int Y { get; set; }
   public int Z { get; set; }
   public int Foam { get; set; }
}

public void DataBase()
{
   using (var db = new LiteDatabase(DB))
   {
      var col = db.GetCollection<Preset>("presets");    
      var preset = new Preset
      {
         Name = CustomPresetName.Text,
         X = Int16.Parse(CustomX.Text),
         Y = Int16.Parse(CustomY.Text),
         Z = Int16.Parse(CustomZ.Text),
         Foam = Int16.Parse(Foam.Text)
       };
       col.Insert(preset);
    }
}

I have simply tried linking the DataGridView with the object as a data source however it doesn't show the data, just the headers. I have also surfed the internet for a similar problem or answer but it seems to be a fairly untouched.

Any help on getting the data to display in the DataGridView is appreciated.


Solution

  • private List<Preset> GetAll()
    {
        var list = new List<Preset>();
        using (var db = new LiteDatabase(DB))
        {
            var col = db.GetCollection<Preset>("presets");
            foreach (Preset _id in col.FindAll())
            {
                list.Add(_id);
            }
        }
        return list;
    }
    
    public void DisplayPresetData()
    {
        PresetView.DataSource = GetAll();
    }