3. Build ManageDishes Window
Add UI Components
First, let’s modify the UI of the ManageDishes window.
- Go to ManageDishes.xaml file.
- Modify backBtn and add a data grid (dishDataGrid), buttons (addDishBtn, deleteDishBtn), text box (nameTxt), text blocks, radio buttons (yesRbtn), and labels. Check the provided code below to understand better. It is for the most outer grid.
<Grid> <Button x:Name="backBtn" Content="Back to Main" HorizontalAlignment="Left" Margin="26,26,0,0" VerticalAlignment="Top" Width="140" Height="45" Click="backBtn_Click"/> <DataGrid x:Name="dishDataGrid" HorizontalAlignment="Left" Height="365" Margin="393,26,0,0" VerticalAlignment="Top" Width="357"/> <Label Content="Name of the dish:" HorizontalAlignment="Left" Margin="26,100,0,0" VerticalAlignment="Top" Width="116"/> <TextBox x:Name="nameTxt" HorizontalAlignment="Left" Height="23" Margin="147,104,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="195"/> <Label Content="Is it breakfast?" HorizontalAlignment="Left" Margin="26,143,0,0" VerticalAlignment="Top"/> <RadioButton x:Name="yesRbtn" GroupName="breakfast" Content="Yes" IsChecked="True" HorizontalAlignment="Left" Margin="147,149,0,0" VerticalAlignment="Top"/> <RadioButton GroupName="breakfast" Content="No" HorizontalAlignment="Left" Margin="266,149,0,0" VerticalAlignment="Top"/> <Button x:Name="addDishBtn" Content="Add Dish" HorizontalAlignment="Left" Margin="26,186,0,0" VerticalAlignment="Top" Width="316" Height="45"/> <TextBlock Text="To delete a dish, please click one from the table." HorizontalAlignment="Left" Margin="26,276,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="27" Width="316"/> <TextBlock Text="Dish ID to delete:" HorizontalAlignment="Left" Margin="26,308,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/> <TextBlock x:Name="idToDeleteTxt" Text="" HorizontalAlignment="Left" Margin="133,308,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/> <Button x:Name="deleteDishBtn" Content="Delete Dish" HorizontalAlignment="Left" Margin="26,346,0,0" VerticalAlignment="Top" Width="316" Height="45"/> </Grid>
Add Database Context
- Go to ManageDishes.xaml.cs file.
- Under declaration for ParentWindow, declare a private MealSuggestionContainer field named _context.
private MealSuggestionContainer _context;
- Inside of the constructor, create a new MealSuggestionContainer for _context.
//create data context _context = new MealSuggestionContainer();
Add Controllers
- Go to ManageDishes.xaml.cs file.
- Add Window_Loaded function. Check the code below.
private void LoadAll() { //get the dishes from the database and make that the source of dishDataGrid var dishes = from d in _context.Dishes select d; dishesOnGrid = dishes.ToList(); dishDataGrid.ItemsSource = dishesOnGrid; } private void Window_Loaded(object sender, RoutedEventArgs e) { //populate dishDataGrid when window loaded LoadAll(); }
- Add addDishBtn_Click function. Check the code below.
private void ClearFields() { //reset the fields for adding new dish nameTxt.Text = ""; yesRbtn.IsChecked = true; } private void addDishBtn_Click(object sender, RoutedEventArgs e) { //when dish name is missing if(nameTxt.Text.Trim() == "") { MessageBox.Show("Please provide the name of a new dish", "Dish Name Missing", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } //create dish with provided info Dish newDish = new Dish() { Name = nameTxt.Text, Breakfast = (bool)yesRbtn.IsChecked }; //add it to database Dish addedDish = null; try { addedDish = _context.Dishes.Add(newDish); _context.SaveChanges(); } catch(Exception ex) { MessageBox.Show(ex.Message); return; } if(addedDish != null) { //refresh dishDataGrid using updated database and reset fields LoadAll(); ClearFields(); MessageBox.Show("Successfully added dish with ID " + addedDish.Id, "Insertion Successful"); } }
- Add dishDataGrid_SelectionChanged function. Check the code below.
private void dishDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { //if one or more items are selected on dishDataGrid if (dishDataGrid.SelectedIndex >= 0 && dishDataGrid.SelectedItems.Count > 0) { //if selected item's type is Dish class if(dishDataGrid.SelectedItems[0].GetType().BaseType == typeof(Dish) || dishDataGrid.SelectedItems[0].GetType() == typeof(Dish)) { //get the selected dish and its id Dish selectedDish = (Dish)dishDataGrid.SelectedItems[0]; idToDelete = selectedDish.Id; //populate idToDeleteTxt with the id idToDeleteTxt.Text = Convert.ToString(idToDelete); } } }
- Add deleteDishBtn_Click function. Check the code below.
private void deleteDishBtn_Click(object sender, RoutedEventArgs e) { //when dish to delete is not selected yet if(idToDelete == 0) { MessageBox.Show("Please select a dish to delete", "Dish ID Missing", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } //confirm MessageBoxResult msgResult = MessageBox.Show("Are you sure to delete this dish?", "Delete Dish", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No); if(msgResult == MessageBoxResult.Yes) { try { //find dish to delete from database Dish dishToDelete = (from d in _context.Dishes where d.Id == this.idToDelete select d).SingleOrDefault(); if(dishToDelete != null) { //delete dish from database _context.Dishes.Remove(dishToDelete); _context.SaveChanges(); MessageBox.Show("Successfully deleted dish with ID " + idToDelete, "Deletion Successful"); //refresh dishDataGrid using updated database LoadAll(); //reset idToDelete idToDelete = 0; idToDeleteTxt.Text = ""; } } catch(Exception ex) { MessageBox.Show(ex.Message); return; } } }
- Go to ManageDishes.xaml file.
- Add
Loaded="Window_Loaded"
for this window. - Add
Click="addDishBtn_Click"
for addDishBtn button. - Add
Click="deleteDishBtn_Click"
for deleteDishBtn button. - Add
SelectionChanged="dishDataGrid_SelectionChanged"
for dishDataGrid data grid.
Move Database Files into Project
This is optional but if you want your app to be completely portable, you should do this. Right now your database is somewhere on your computer. You are going to move it into the project.
- Find the database files with file name extensions, .mdf and .ldf. Your C:\Users\<Your User Name> directory is worth checking.
- Move them (both .mdf and .ldf files) into the bin\Debug directory of this C# project.
- Go to App.config file.
- Find connectionStrings tag and replace
initial catalog=MealSuggestion;
withAttachDbFilename=|DataDirectory|\MealSuggestion.mdf;
. If you named the database file differently, match that in place of MealSuggestion.mdf.
Check Your Code
After following this chapter, your app should be able to:
- read (displayed in the dishDataGrid), add, and delete dishes on the ManageDishes window
- work properly even if you move the project to another computer