After completion of today's lab, you should be able to
A lot of different applications, whether Windows, Web, or console, use a relational database to store the program's data. Inside the program, queries written in Structured Query Language (SQL) are used to retrieve and manipulate the data.
.NET provides a number of classes to simplify the process of reading and writing to databases. Using these classes produces code that is easily ported from one database to another (for example, develop with Access and move to SqlServer)
We will use MS Access to create a very small database to use with Lab 9
Activity: - Create a MS Access Database to use with Lab9
Lab9 stored in your u:\ driveCourses CourseId the primary key and set its Data Type to AutoNumber. Courses
We can use Access to add or edit data in the database tables directly. Let us add some courses to our Course table
Activity: - Add records to Courses
CourseId column and using the tab key to advance from one column to the next.Datasets are in-memory representations of our database structure and data. We can fill datasets with database data, work with the data in our application, and then save the data back to the database when it changes
Activity: - Create new WindowsUI project in solution U:\Lab9
WindowsUI in solution U:\Lab9.MainForm.cs and the text displayed in MainForm's title bar to Lab 9Activity: - Add a DataSet for your Courses table
WindowsUI project Lab9 access databaseCourses table as your Database object and accept the default Lab9DataSet nameLab9DataSet.xsd file added in Solution Explorer
Activity: - Displaying the Data in a DataGridView
MainForm in Design ViewMainFormMainForm and in its designer trayIn addition to the DataGridView, we also have available a Details view
Activity: - Displaying the Data in a Details View
DetailsViewFormDetailsViewFormDetailsViewFormThe built-in DataGridView and Details view controls are useful, but more often we need to design our own interface
Many of the .net controls allow binding with a data source
Activity: - Data binding to controls
CourseViewerFormCourseViewerFormSurprise, nothing happens by magic. Add a Load event handler and fill the DataSet with the following code.
private void CourseViewerForm_Load(object sender, EventArgs e)
{
this.coursesTableAdapter1.Fill(this.lab9DataSet1.Courses);
}
Activity: - Binding your ListBox to the coursesBindingSource
Activity: - Binding your TextBoxes to the coursesBindingSource
CourseViewerForm Design View, select the first TextBox and use the Properties window to set the DataBinding Text property to coursesBindingSource - CourseIDActivity: - Saving the data
CourseViewerForm to save the changed data
private void saveButton_Click(object sender, EventArgs e)
{
this.Validate();
this.coursesBindingSource.EndEdit();
this.coursesTableAdapter1.Update(this.lab9DataSet1.Courses);
}