Search code examples
c#winforms

How to programmatically add a small database to a Windows Forms project?


I recently finished my first little windows form app, but I used Access to make a database to populate the dropdowns, and it seems to want the user to have a silly database driver. I decided given how small the database is it would be better to just write it all out.

Basically I need to make 3 tables with 5-6 items each, with a display value and a secondary value, and use them to populate my dropdowns.

What's the best practice for something like this? make a class with two values, and put them in an ArrayList? populate it one item at a time and assign the secondary value later? or is there a smoother way that's more built into C#? I made the app for my portfolio so I want to make sure its done "right".

Clarification: The data are read-only. The user will not be able to edit these values.


Solution

  • The following uses Dapper which is added to your project as a NuGet package. Getting started page.

    To interact with a table in a database create a class where the properties represent a column in the table. In the class Category ToString is overridden so that when presented in a ComboBox the overridden value, name of the category is shown.

    Microsoft Access is fine to get your feet wet but better off using SQLite which is installed as an NuGet package here.

    
    /*
     * For the dropdown, set DropDownStyle to DropDownList
     */
    public partial class Form1 : Form
    {
        private BindingList<Category> _bindingCategories;
        public Form1()
        {
            InitializeComponent();
            Shown += Form1_Shown;
        }
    
        private async void Form1_Shown(object sender, EventArgs e)
        {
            DataOperations dataOperations = new();
            
            _bindingCategories = new BindingList<Category>(
                await dataOperations.GetCategories());
    
            CategoriesComboBox.DataSource = _bindingCategories;
        }
    
        private void GetCategoryButton_Click(object sender, EventArgs e)
        {
            Category category = _bindingCategories[CategoriesComboBox.SelectedIndex];
            MessageBox.Show($"{category.Identifier} {category.CategoryName}");
        }
    }
    
    // place in its own file
    public class Category
    {
        public int Identifier { get; set; }
        public string CategoryName { get; set; }
        public override string ToString() => CategoryName;
    }
    // place in its own file
    public class DataOperations
    {
        private IDbConnection _cn = new OleDbConnection("Your connection string");
        public async Task<List<Category>> GetCategories()
            => (await _cn.QueryAsync<Category>(
                "SELECT Identifier, CategoryName FROM Categories")).AsList();
    }
    

    Screenshot

    enter image description here