BLOG.CSHARPHELPER.COM: Display information about database records selected from a list without data binding in C#
Display information about database records selected from a list without data binding in C#
The example Initialize a list from a database table without data binding in C# explains one way to fetch values from a database table and use them to initialize a ListBox. This example extends that one to display information about records when the user selects one in the ListBox.
See the previous example to learn how the program defines its database connection and initializes the 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.GetValue(1).ToString();
txtYear.Text = reader.GetValue(2).ToString();
txtISBN.Text = reader.GetValue(3).ToString();
txtPages.Text = reader.GetValue(4).ToString();
// Clean up.
reader.Close();
Conn.Close();
}
The code builds a 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 a OldDbDataReader object. It then calls that object's Read method to get the first (and only) result record.
The code then copies the returned record's values into the appropriate TextBoxes.
Comments