Title: Display database records without data binding in C#
Many programs use data binding to display database records. That method is easy (at least as far as the code you write is concerned), but it's not very flexible. This example shows how you can display database records without data binding. It requires more code behind the scenes but gives you more direct control over what's happening.
The example Initialize lists from databases without binding in C# explains the basic technique. See that post to learn how this program defines its database connection and initializes its ListBox with book titles.
The following code shows the program displays information about a book when the user selects it from the ListBox.
// Display information about the selected title.
private void lstTitles_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstTitles.SelectedIndex < 0) return;
// Make a command object to get information about the title.
string title = lstTitles.SelectedItem.ToString().Replace("'", "''");
OleDbCommand cmd = new OleDbCommand(
"SELECT * FROM Books WHERE Title='" +
title + "'",
Conn);
// Execute the command.
cmd.Connection = Conn;
Conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
reader.Read();
// Display the text data.
txtURL.Text = reader["URL"].ToString();
txtYear.Text = reader["Year"].ToString();
txtISBN.Text = reader["ISBN"].ToString();
txtPages.Text = reader["Pages"].ToString();
// Clean up.
reader.Close();
Conn.Close();
}
The code builds a SQL SELECT statement to get all of the data from the Books table for the selected book. Note that it uses Replace to convert single quotes into pairs of single quotes in the book's title. If the book's title contains a single quote, as in "Visual Basic 2012 Programmer's Reference," that quote would match with the single quotes in the SELECT statement and confuse the database. Replacing quotes with pairs of quotes tells the database that a pair of quotes represents a single quote in the title's value so the query will work properly.
After composing the SELECT statement, the code executes it, saving the result of the ExecuteReader method in an OldDbDataReader object. It then calls that object's Read method to get the first (and only) result record.
The code finishes by copying the returned record's values into the appropriate TextBox controls.
Download the example to experiment with it and to see additional details.
|