• 0

C# using arrays and outputting to dataGridView


Question

Hello all,

I'm trying to write a program using arrays and outputting specific data into and dataGridView box. I seem to have the code right, at least it is liking what I have, but I am not seeing it out put in the formLoad_1 event.

 

If anyone would be able to help me out that would be awesome! thank you!

 

Here is the code (sorry its a little messy, trying to do to many things at once.)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Project_Diving_Arrays
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string[] diverArray = new string[50];
        double[] overallArray = new double[50];
        int[] place = new int[50];
        int numDivers, numRounds, numJudges;

        private void gB_Program_Enter(object sender, EventArgs e)
        {
            //Looking at display list boxx on demo
            //foreach (string str in diverArray)
            //{
            //    numDivers.ToString("n1");
            //}
            //foreach (double num in overallArray)
            //{
            //    numRounds.ToString("n1");
            //}
            //try
            //{
            //    StreamReader inputFile;
            //    inputFile = File.OpenText("DiverData.csv");
            //    int index = 0;
            //    while (!inputFile.EndOfStream && index < 50)
            //    {
            //        string temp = inputFile.ReadLine();
            //        string[] tokens = temp.Split(',');
            //        numDivers = int.Parse(tokens[0]);
            //        numRounds = int.Parse(tokens[1]);
            //        numJudges = int.Parse(tokens[2]);
            //        index++;
            //    }
            //    for(int i=0;i<numDivers;i++)
            //    {
            //        diverArray[i]=inputFile.ReadLine();
            //    }

            //    DisplayGridview();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
        }


        private void DisplayGridview()
        {

            DataTable table = new DataTable();
            table.Columns.Add("Place", typeof(int));
            table.Columns.Add("Names", typeof(string));
            table.Columns.Add("Overall", typeof(double));

            //Add table Rows
            //
            for (int i = 0; i < (double)numDivers; i++)
            {
                table.Rows.Add(place[i], diverArray[i], overallArray[i]);
            }
            //for (int i = 0; i < place; i++)
            //{
            //    table.Rows.Add(place[i].numDiver, place[i].Time);
            //}
            //for (int i = 0; i < MyRec.Count; i++)
            //{
            //    table.Rows.Add(MyRec[i].Name, MyRec[i].Time);
            //}
            dataGridView1.DataSource = table;
        }

        private int FindIndex(string[] sArray, string value)
        {
            bool found = false;
            int index = 0;
            int position = -1;

            // Search the Array
            while (!found && index < sArray.Length)
            {
                if (sArray[index] == value)
                {
                    found = true;
                    position = index;
                }
                index++;
            }
            return position;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                StreamReader inputFile;
                inputFile = File.OpenText("DiverData.csv");
                int index = 0;
                while (!inputFile.EndOfStream && index < 50)
                {
                    string temp = inputFile.ReadLine();
                    string[] tokens = temp.Split(',');
                    numDivers = int.Parse(tokens[0]);
                    numRounds = int.Parse(tokens[1]);
                    numJudges = int.Parse(tokens[2]);
                    index++;
                }
                for (int i = 0; i < numDivers; i++)
                {
                    diverArray[i] = inputFile.ReadLine();
                }

                DisplayGridview();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Thanks again for the help and please let me know if I have forgotten any important information to post.

Dive project.tiff

DiverData This should be a CSV file.txt

Link to comment
Share on other sites

8 answers to this question

Recommended Posts

  • 0

Well, I don't want to do your homework for you, but I don't mind helping a bit. ;)

 

Part of your problem is that you have 2 lots of data in your CSV file; first row has your settings (numDrivers etc) and the rest is your actual data. However, you're loading your settings variables inside a loop, so once it gets to the second line of data, you'll get an error as it tries to set numDrivers to 'Thompson', having previously been set to 15.

 

What you need to do is read the FIRST line of data, split into your tokens var, then set your numDrivers etc.  After that, THEN setup a loop to read to EndOfStream, setting your driverArray for each line.  This will give you an array for each line of data.

 

ie:

Thompson,,,,,,,,,,
Chang,,,,,,,,,,
Ellis,2.3,6,6,5,6,6.5,7,5.5,6,6.5
Johnson,2.2,6.5,5.5,6,5,7,6.5,7,6,7

 

From there, you'll need to parse your data further for the fields in your datatable, splitting the diverArray elements for the Place, Names & Overall fields.

 

BTW: numDrivers starts off as an int, and then you later recast it as a double in the DisplayGridview method. Did you mean to do that?

Link to comment
Share on other sites

  • 0

Remove the try...catch and run it again. You've got problems with your input code and that's keeping you from seeing what it is in the debugger.

 

I'm assuming the first line should only be read once?

Link to comment
Share on other sites

  • 0

Why do you have a second loop to add to the diverArray? Shouldn't that be done inside the main while loop?

 

That actually may be one of the causes of your problem. IIRC (haven't used C# in awhile), doesn't ReadLine tell the StreamReader inputFile to read the next line?

 

In your While loop you read inputFile until the end of the stream, then you loop again telling it to read more lines but wouldn't it still be at the end of the stream since you didn't reset the stream?

 

Try moving the diverArray inside your While loop, using your 'index' variable instead of 'i' to step through the array.

 

May be wrong though, it's late here, I'm getting tired, and I haven't done file reading in C# in awhile.

 

EDIT: Ah, I see.....numDivers is defined in the CSV file and you use the first while loop to parse that value. I still think using ReadLine in two different places may be where you are going wrong. You never restart the stream so it is picking up where it left off which if I understand your code correctly, is at the very end of the file already.

Link to comment
Share on other sites

  • 0

Eric:

I removed the try catch and its still not outputting. The gB_Program_Enter was for the groupBox that I initially placed the program in, but soon realized it was wrong, but didn't want to delete it yet. I have now deleted it and still having the same results.

 

Naginsan:

Your understanding is correct. I want the code to continue running through because I will be recalling it, for another 3 tries. Calculating the scores for 3 different rounds.

I also tried moving the diverArray and changing the variables but with no results.

Link to comment
Share on other sites

  • 0
Naginsan:

Your understanding is correct. I want the code to continue running through because I will be recalling it, for another 3 tries. Calculating the scores for 3 different rounds.

I also tried moving the diverArray and changing the variables but with no results.

Have you tried adding a breakpoint after you set the array to make sure the array has the data you expect in it? If not you may want to do that and inspect the array data, if it has the right data then that part is right but your display code is wrong, otherwise you are not correctly adding data to the array.

 

EDIT: I'm heading off to bed but I tried loading your program myself and something is fundamentally wrong with it that I'm not figuring out just by looking it over.....it appears it is not even hitting the Form1_Load function like it should be. A quick search found this: http://stackoverflow.com/questions/5197695/form1-load-not-firing-even-after-adding-handler

 

In short try tapping the OnLoad function instead of Form1_Load, it's apparently more reliable and may help point out errors.

Link to comment
Share on other sites

  • 0

I found out what was wrong. I was trying to call out int Place as an array, when it should not have been an array. The program was trying to read the string into the gridDataView box when it should not have been reading it at all. Also, I replaced the place with i+1 calling out the numbering in the column and labeling it places at the same time.

 

Thanks for the help. I'm sure I'll have more problems with this program haha.


FloatingFatMan:

I thought type casting the double would help with the problem but didn't. Only lead to a different direction. I changed a few things and what you said helped as well. I was not creating columns correctly or calling them out correctly at that.

 

Thanks for your input!

Link to comment
Share on other sites

  • 0

Here is where your problem was:

while (!inputFile.EndOfStream && index < 50)
{
     string temp = inputFile.ReadLine();
     string[] tokens = temp.Split(',');
     numDivers = int.Parse(tokens[0]); // These three lines read the header from your data file.
     numRounds = int.Parse(tokens[1]); // You are calling them in a loop when they should only
     numJudges = int.Parse(tokens[2]); // be only called once when the file is first read.
     index++;
}

If you move those outside the loop and only call the initial ReadLine() then those it will work.

You should be getting an exception when your code tries to read the second line in the file because it's trying to cast the first diver's name to an integer since it thinks it's reading the header with the data counts in it again. That's why I suggested you remove the try...catch block so you can see where it's failing. I copied your code into a class and ran it and immediately got a messagebox with the error "Input string not in correct format."

 

If you're catching exceptions for error display purposes it's usually best to only use specific exceptions that you're expecting rather than all of them. (i.e.: Only catch "FormatException" or "IOException")

Link to comment
Share on other sites

This topic is now closed to further replies.