Courses.csv from the application's working directory and displays three columns.Continue your completed 0.5 First Day application. Create a CSV file containing course numbers, course names, and credits. Add a button that opens the file and displays its contents in a table, then sort the table by clicking its column headings.
Goal: Create structured data in a file, load it into an application, and organize it in different ways.
Close Visual Studio. Copy the entire completed solution folder and name the backup First Day 0.5 Backup LastName. Open LastName.sln from your original working folder. Keep the working folder and solution names unchanged.
Check the shopping-list save and load buttons and the weather feature from 0.5. Close the running application before editing.
CSV means comma-separated values. Each row represents one course, and commas separate its three values. The first row names the columns.
Use Notepad to create a plain-text file. Paste the complete example, including its first row. These sample courses let you check text sorting, decimal credits, and numeric sorting.
Course Number,Course Name,Credits
CS 102,Object-Oriented Programming,4
ENG 101,College Writing,3
CS 001,Introduction to Computing,2
ART 110,"Art, Design and Technology",1.5
CAP 200,Capstone Studio,10Courses.csv in your solution folderChoose File > Save As. Browse to the working LastName folder containing LastName.sln. Set Save as type to All files, enter Courses.csv, choose UTF-8 encoding, and save. Confirm the filename is Courses.csv, not Courses.csv.txt.
Keep the header exactly as shown and in the same order. Each course must have a number, name, and nonnegative numeric credit value. Use a period for decimal credits. A course name containing a comma must be enclosed in double quotes, as shown for Art, Design and Technology.
Course numbers are text identifiers: CS 001 should keep its leading zeros. Credits are numbers: 10 should sort after 4 in ascending order. You will add a course of your own after testing the example.
In Solution Explorer, open FirstDayScenario/MainWindow.xaml and switch to XAML source view. Find the shopping-list StackPanel in Grid row 3 and locate its matching closing tag, after both shopping-list buttons. Insert this entire block immediately after that closing tag and before the existing output TextBox in Grid row 5. The new panel must be a direct child of the existing Grid. Row 4 already exists in the Grid row definitions.
<StackPanel Grid.Row="4"> <TextBlock Text="Courses" FontWeight="Bold" VerticalAlignment="Center" Margin="5,10,0,0" /> <Button x:Name="loadCoursesButton" HorizontalAlignment="Left" Content="Load courses CSV" Width="125" Margin="5" Click="loadCoursesButton_Click" /> <DataGrid x:Name="coursesDataGrid" AutoGenerateColumns="True" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="True" ColumnWidth="Auto" Margin="5" /> </StackPanel>

The DataGrid generates its columns from the loaded table and allows column sorting. Save the file. The loadCoursesButton_Click method has not been added yet; complete the next task before building.
In Solution Explorer, expand References under the FirstDayScenario project and confirm System.Data is present. If it is missing, right-click References, choose Add Reference, and select System.Data under Assemblies > Framework. The supplied CSV reader uses framework classes and requires no Microsoft.VisualBasic reference.
CourseCsv.cs in the FirstDayScenario projectRight-click the Business Classes folder in the FirstDayScenario project, choose Add > Class, name the file CourseCsv.cs, and click Add. Open that file, select all generated contents, and replace them with the complete code below. Include the using statements, namespace, class, and all braces. This code goes in the new CourseCsv.cs file, not MainWindow.xaml.cs.
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
namespace FirstDayScenario
{
/// <summary>
/// Represents a CSV file containing course information.
/// </summary>
public static class CourseCsv
{
private static readonly Regex FieldPattern = new Regex("\\G[ \\t]*(?:\"(?<quoted>(?:[^\"]|\"\")*)\"[ \\t]*|(?<plain>[^\",\\r\\n]*))(?<end>,|\\r\\n|\\r|\\n|\\z)");
/// <summary>
/// Loads a CSV file containing course information into a DataTable.
/// </summary>
/// <param name="fileName">The name of the course CSV file.</param>
/// <returns>An in-memory DataTable containing course information.</returns>
public static DataTable Load(string fileName)
{
DataTable courses = new DataTable();
courses.Columns.Add("CourseNumber", typeof(string));
courses.Columns.Add("CourseName", typeof(string));
courses.Columns.Add("Credits", typeof(decimal));
bool headerFound = false;
foreach (string[] fields in ReadRows(File.ReadAllText(fileName)))
{
if (!headerFound)
{
if (fields.Length != 3 ||
!string.Equals(fields[0], "Course Number", StringComparison.OrdinalIgnoreCase) ||
!string.Equals(fields[1], "Course Name", StringComparison.OrdinalIgnoreCase) ||
!string.Equals(fields[2], "Credits", StringComparison.OrdinalIgnoreCase))
{
throw new FormatException("The first row must be: Course Number,Course Name,Credits");
}
headerFound = true;
continue;
}
decimal credits;
if (fields.Length != 3 ||
string.IsNullOrWhiteSpace(fields[0]) ||
string.IsNullOrWhiteSpace(fields[1]) ||
!decimal.TryParse(fields[2], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out credits) ||
credits < 0)
{
throw new FormatException(
"Each row needs a course number, course name, " +
"and nonnegative numeric credits.");
}
courses.Rows.Add(fields[0], fields[1], credits);
}
if (!headerFound)
{
throw new FormatException("The CSV file is empty.");
}
if (courses.Rows.Count == 0)
{
throw new FormatException("Add at least one course beneath the CSV header.");
}
return courses;
}
private static IEnumerable<string[]> ReadRows(string text)
{
int position = 0;
while (position < text.Length)
{
int rowStart = position;
string delimiter;
List<string> fields = new List<string>();
do
{
Match match = FieldPattern.Match(text, position);
if (!match.Success)
{
throw new FormatException("Invalid CSV formatting near character " + (position + 1) + ".");
}
string value = match.Groups["quoted"].Success
? match.Groups["quoted"].Value.Replace("\"\"", "\"")
: match.Groups["plain"].Value;
fields.Add(value.Trim());
position += match.Length;
delimiter = match.Groups["end"].Value;
}
while (delimiter == ",");
if (!string.IsNullOrWhiteSpace(text.Substring(rowStart, position - rowStart)))
{
yield return fields.ToArray();
}
}
}
}
}The supplied reader uses a regular expression to read CSV fields and checks the header and each row before returning the table. It handles quoted course names and stores credits as numbers so they sort correctly.
MainWindow.xaml.csExpand MainWindow.xaml in Solution Explorer and open MainWindow.xaml.cs. At the very top of the file, with its existing using statements and above the namespace line, add any of these lines that are missing. Keep the other using statements. Do not duplicate lines already present.
using System;
using System.IO;
using System.Windows;loadWeatherButton_ClickIn MainWindow.xaml.cs, find the declaration of the existing loadWeatherButton_Click method. Place the cursor on a blank line after its closing brace and paste the complete method below. It belongs inside the MainWindow class, outside every other method.
Keep loadWeatherButton_Click and its entire body. Keep the constructor, GetForecastAsync, and every existing event handler. If you already created an empty loadCoursesButton_Click method, replace that empty method with this one instead of adding a second copy.
private void loadCoursesButton_Click(object sender, RoutedEventArgs e)
{
string coursesPath = "Courses.csv";
if (File.Exists(coursesPath))
{
try
{
// Only replace the current table after the entire file is valid.
System.Data.DataTable courses = CourseCsv.Load(coursesPath);
this.coursesDataGrid.ItemsSource = courses.DefaultView;
this.textOutput.Text = courses.Rows.Count + " courses loaded. Click a column heading to sort.";
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is FormatException)
{
MessageBox.Show(this, ex.Message, "Unable to load courses", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
}The button reads Courses.csv from the application's working directory. After a valid file is read, ItemsSource connects its table to the DataGrid. If the file is invalid, a message explains the problem and the previous table stays in place. If the file is missing, this handler does nothing.
Keep your original CSV in the solution folder. For the supplied project's default Debug run settings, copy it into FirstDayScenario\bin\Debug beside FirstDayScenario.exe. Build once first if this folder does not exist. The relative filename in the handler is resolved from the application's working directory; if you configured a different working directory, put the copy there instead. Whenever you edit the original CSV, replace this run-folder copy before loading again.
Choose Build > Build Solution. If System.Data cannot be found, check its framework reference. If CourseCsv cannot be found, check that CourseCsv.cs was added to the project and contains the complete supplied code. The new button's Click value and C# method must both be spelled loadCoursesButton_Click.
Load courses CSVThe button loads the run-folder copy of Courses.csv directly; there is no file picker. Confirm that five courses appear. The course name Art, Design and Technology should occupy one cell even though it contains a comma. The course number CS 001 should retain its zeros.
Click CourseNumber to sort by course number, then click it again to reverse the order. Repeat with CourseName. Click Credits: ascending order should be 1.5, 2, 3, 4, 10. Click it again to reverse the order.
Sorting rearranges the displayed rows. It does not change the CSV file. You do not need to write a separate sorting method; the supplied DataGrid provides column sorting.
Open Courses.csv in Notepad, add a new row with a course number, course name, and numeric credits, and save. Replace the run-folder copy with this updated file. Return to the application, click Load courses CSV, to read the updated file. Confirm that six courses appear. Loading again replaces the table rather than adding duplicate rows. Edit courses in the CSV file; the displayed table is read-only.
In Notepad, temporarily change one credit value to three and save. Replace the run-folder copy, then try loading the file. Confirm that an error message appears and the six previously loaded courses remain visible. Change the value back to a number, save, replace the run-folder copy, and load successfully again.
Click New student before Have breakfast or Fill backpack. Check both clothing choices and the shopping-list save and load buttons. Load weather using Chicago's coordinates from 0.5: -87.6298 for Longitude and 41.8781 for Latitude. Confirm the JSON still appears in the browser area.
Confirm the solution builds, your six-course CSV loads, all three columns sort, and the earlier features still work. Restore valid data in Courses.csv before submitting.
Close Visual Studio. Create a ZIP of the working LastName folder. Open the ZIP and confirm it includes LastName.sln, the FirstDayScenario project folder, the new CourseCsv.cs file inside its Business Classes folder, and Courses.csv in the solution folder.
Upload the ZIP to First Day 0.6 in the Feedback System. Review the results and correct any required issues. Submit the Feedback System submission URL to the 0.6 First Day Assignment in Canvas.