1

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:

enter image description here

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;
                }
            }
HelpNeeder
  • 6,383
  • 24
  • 91
  • 155
  • 2
    "\r\n" use Environment.NewLine instead it is better – Nighil Nov 19 '11 at 06:49
  • @Nighil: Well, what's the difference? Please post link so I can read while wait for an answer of my question :) – HelpNeeder Nov 19 '11 at 06:51
  • 1
    It's better because if you port the code to Mono later for cross-platform use, it'll work without changes - Linux, for example, uses only `\n` as a line ending. It's also not a hard-coded literal value. – Ken White Nov 19 '11 at 07:01
  • Plus you don't really need to print a final "\r\n" or Environment.NewLine at the end of your MessageBox.Show. – MPelletier Nov 19 '11 at 09:08
  • @MPelletier: This is true, I have rebuild command prompt to form application. Thanks for a pointer. – HelpNeeder Nov 19 '11 at 09:19

1 Answers1

3

I'm not giving you the entire answer, because that would defeat the purpose of the assignment and you wouldn't learn anything. However, I can give you ideas on where to start to solve the problem.

Your output starts in the block starting with if (drMagazines.HasRows). The code within that block is where you need to make your changes.

You need to change it so that instead of printing out the column headings and then the content of each row, you print a separator that includes the magazine number, a line ending (Environment.NewLine) and then separate rows that have titles and then content.

You have the necessary information in your code now - you have comments where you populate the column headings and then populate the data by row. Change that so that you populate a single heading and then populate the row content for that heading. A suggestion would be to change it from two loops to one - read a column heading, and then the row content that it contains. You can add any additional content or formatting during that loop for each item.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • Ok, I see. I have done what u have suggested, but how to get rid of unwanted fields? Well, not so much unwanted, but for example change ID of column to 'magazine number'? – HelpNeeder Nov 19 '11 at 07:03
  • 1
    You can add any text you want, anywhere you want. Read the code: `displayMags.txtDisplayMags.Text +=` - you can use `+= "AnythingYouWant" + AnythingElseYouWant`, as long as what you want to add can be converted to text. The point of the assignment is so you think about what you're trying to do and think through the changes you need to make to get there. The hints are all in the code you posted, if you read it and understand what it says. :) – Ken White Nov 19 '11 at 07:15
  • Ok, I do see the point with inserting some strings of text before the query result, but since it's reading the db it pulls out values and won't me display anythings between each row. Should I just use a counter which would count entries from a loop, or use the number from ID of each entry? – HelpNeeder Nov 19 '11 at 08:48
  • It will allow you to insert anything anywhere you want - you can read a column that contains `Fred`, insert something after the third and fifth character, and end up with `Frieda`. You need to actually read and understand the code you're writing. :) You can read a row, insert a paragraph of text about the current weather, and then read the next row. IOW, the data is yours to use as you need it - that may be the entire point of this assignment. – Ken White Nov 19 '11 at 08:54
  • Your complicated but I do see your point :) I will try to play a little with the code. – HelpNeeder Nov 19 '11 at 08:58
  • Ok, It seems like it works like it should, but is this how you have imagined? - My last Edit, at the very bottom of my OP. – HelpNeeder Nov 19 '11 at 09:35
  • It looks fine for the purposes of your lesson. Nicely done - I think your professor will be impressed. :) – Ken White Nov 19 '11 at 17:49