This post lists the C# code-behind in our WPF SQLite ToDo project. This is the MainWindow.xaml.cs file.
Some of the most interesting code is found in this file. The first thing the code does after the GUI is loaded, is to call the method LoadToDoList(). This does two things. It goes out to the database and gets a list of ToDos and stores those in our field called todos. It is a generic list of todos. Next, we need to “wire up” that in-memory list to the GUI ListBox so that the user can see the list.
Here is the MainWindow.xaml.cs file listing.
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; namespace ToDoList { public partial class MainWindow : Window { List<ToDo> todos = new List<ToDo>(); public MainWindow() { InitializeComponent(); LoadToDoList(); } private void LoadToDoList() { todos = SQLiteDataAccess.LoadToDo(); WireUpToDoList(); } private void BtnRefreshList_Click(object sender, RoutedEventArgs e) { LoadToDoList(); } private void WireUpToDoList() { // attach the in-memory list to the ListBox listToDoListBox.ItemsSource = null; // important to first make null listToDoListBox.ItemsSource = todos; } private void BtnAddToDo_Click(object sender, RoutedEventArgs e) { ToDo td = new ToDo(); td.Name = txtboxName.Text; td.Status = txtboxStatus.Text; if (!string.IsNullOrEmpty(txtboxName.Text.Trim()) && !string.IsNullOrEmpty(txtboxStatus.Text.Trim())) { SQLiteDataAccess.SaveToDo(td); txtboxName.Text = ""; txtboxStatus.Text = ""; } } private void ListToDoListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListBox lb = sender as ListBox; // user can only select one row at a time, but here we must use // SelectedItems (plural) because of the template. foreach (object o in lb.SelectedItems) { txtboxEditId.Text = (o as ToDo).Id.ToString(); txtboxEditName.Text = (o as ToDo).Name; txtboxEditStatus.Text = (o as ToDo).Status; } } private void BtnSaveToDo_Click(object sender, RoutedEventArgs e) { // We must update the record in the database with the // object var td = new ToDo(); td.Id = Convert.ToInt32(txtboxEditId.Text); td.Name = txtboxEditName.Text; td.Status = txtboxEditStatus.Text; SQLiteDataAccess.UpdateToDo(td); } private void BtnDeleteToDo_Click(object sender, RoutedEventArgs e) { var td = new ToDo(); td.Id = Convert.ToInt32(txtboxEditId.Text); td.Name = txtboxEditName.Text; MessageBoxResult r = MessageBox.Show("Are you sure you want to permanently delete " + td.Name + "?", "Delete To Do", MessageBoxButton.OKCancel, MessageBoxImage.Warning); if (r == MessageBoxResult.OK){ SQLiteDataAccess.DeleteToDo(td.Id); txtboxEditId.Text = ""; txtboxEditName.Text = ""; txtboxEditStatus.Text = ""; } } } }