Home > Back-end >  How to use a Class as a database for DataGridView in C# without an SQL?
How to use a Class as a database for DataGridView in C# without an SQL?

Time:10-13

I have to use a class as a database for a winforms project in c# for a schoolproject but we haven't learned mySQL yet as. How do i use a class as a database without mySQL?

CodePudding user response:

In beware of dislikes, I want suggest to use Singleton pattern to create a class which would store some List<T> as a "database table". There also may be few Lists, each one would represent different "database tables" (public List<T> Customers, public List<T> Sales etc.).

public sealed class RuntimeDatabase
{
    private List<Person> persons = new List<Person>();

    // List used as database table
    public List<Person> Persons
    {
        get => persons;
        private set => persons = value;
    }

    // Singleton
    private static readonly RuntimeDatabase instance = new RuntimeDatabase();

    public static RuntimeDatabase Instance => instance;

    private RuntimeDatabase() { }
}

You can use it elsewhere:

public partial class MainWindow : Window
{
    private readonly RuntimeDatabase DB = RuntimeDatabase.Instance;

    private void GetPersons()
    { 
        dataGrid.ItemsSource = DB.Persons;
    }

    private void AddPerson()
    {   
        Person p = new Person();
        p.Name = "John Wick";
 
        DB.Persons.Add(p);
    }

    private void RemovePerson()
    {   
        Person p = new Person();
        p.Name = "John Wick";
 
        DB.Persons.Remove(p);
    }
}

Or create custom methods-wrappers in RuntimeDatabase class to imitate Insert, Update, Delete, Truncate, Select etc. actions.

Sketch:

public sealed class RuntimeDatabase
{  
    //...

    public List<Person> Select(Func<Person, bool> func)
    {
        return persons.Where(func).ToList();
    }

    public void Insert(Person person)
    {
        persons.Add(person);
    }

    public void Update(Person person)
    {
        persons = persons.Select(x => 
        { 
            if (x.ID == person.ID) // It's preferred to have an ID property to unique each Person (some kind of Primary Key)
            {
                x.SomeProperty = person.SomeProperty;
            }

            return x;
        }).ToList();
    }

    public int Delete(Predicate<Person> predicate)
    {
        return persons.RemoveAll(predicate); // Count of removed elements
    }

    public void Truncate()
    {
        persons.Clear();
    }
}

Of course you can create a methods to save it to some file before application exit and load back at application startup.

Person used in example is simple model class:

public class Person 
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string SomeProperty { get; set; }
}

Feel free to throw mud at me.

  • Related