As title states, my piece of code which was from an example provided by my professor.
My output is:
MagazineID Title Publisher Price SubscriptionRate
1 People Times Inc. 4.95 19.95
2 Car and Driver Hachetter Inc. 3.95 19.99
Code:
private void btnShowMags_Click(object sender, EventArgs e)
{
// Creating new instance of the DisplayMags form.
DisplayMags displayMags = new DisplayMags();
// find the path where the executable resides
string dbPath = Application.StartupPath;
// Providing a path to the MS Access file.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="
+ dbPath + @"\..\..\..\..\Magazines.mdb; User Id=admin; Password=";
// Creating a new connection and assigning it to a variable.
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = connString;
// Creating a new instance for a command which we will use later.
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
// declare and instantiate the command
OleDbCommand cmdMagazines = new OleDbCommand();
cmdMagazines.CommandText = "select * from magazine";
cmdMagazines.Connection = conn;
OleDbDataReader drMagazines;
try
{
// open the connection
conn.Open();
// retrieve data from the data source to the data reader
drMagazines = cmdMagazines.ExecuteReader();
if (drMagazines.HasRows)
{
// populate the column headings
for (int i = 0; i < drMagazines.FieldCount; i++)
displayMags.txtDisplayMags.Text += drMagazines.GetName(i) + " ";
displayMags.txtDisplayMags.Text += "\r\n";
// populate the data by row
while (drMagazines.Read())
{
for (int i = 0; i < drMagazines.FieldCount; i++)
displayMags.txtDisplayMags.Text += drMagazines.GetValue(i) + " ";
displayMags.txtDisplayMags.Text += "\r\n";
}
}
}
catch (Exception ex)
{
// Displaying any errors that might have occured.
MessageBox.Show("Error opening the connection: " + ex.Message + "\r\n");
}
finally
{
// Closing connection after task was completed.
conn.Close();
}
// Displaying DisplayMags form, assuring that earlier form
// will not be accessible. Show() let us access all forms.
displayMags.ShowDialog();
}
And, I am trying to make it look like this:
EDIT. This work, but does this represent correct programming practices?
if (drMagazines.HasRows)
{
while (drMagazines.Read())
{
displayMags.txtDisplayMags.Text += "=== Magazine " +
drMagazines.GetValue(0) + " ===" + Environment.NewLine +
drMagazines.GetValue(1) + Environment.NewLine +
drMagazines.GetValue(2) + Environment.NewLine +
drMagazines.GetValue(3) + Environment.NewLine +
drMagazines.GetValue(4) + Environment.NewLine +
Environment.NewLine;
}
}