• 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

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?

  • 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.

  • 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.

  • 0
  On 20/03/2015 at 03:02, White Wolf said:
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.

  • 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!

  • 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")

This topic is now closed to further replies.
  • Posts

    • OpenAI exposes secret propaganda campaigns tied to multiple countries by David Uzondu Back in February, OpenAI shut down accounts that were busy developing Chinese surveillance tools aimed at the West. These tools were designed to snoop on social media, look for anti-China sentiment and protests, and report back to Chinese authorities. Now, OpenAI has announced it has disrupted even more shady operations, and not just those tied to China. In a report released Thursday, the company detailed how it recently dismantled ten different operations that were misusing its artificial intelligence tools. One of the China-linked groups, which OpenAI called "Sneer Review," used ChatGPT to churn out short comments for sites like TikTok, X, and Facebook. The topics varied, from U.S. politics to criticism of a Taiwanese game, where players work against the Chinese Communist Party. This operation even generated posts and then replied to its own posts to fake real discussions. What is particularly interesting is that the group also used ChatGPT to write internal performance reviews, describing how well they were running their influence campaign. Another operation with ties to China involved individuals posing as journalists and geopolitical analysts. They used ChatGPT to write social media posts and biographies for their fake accounts on X, translate messages from Chinese to English, and analyze data. OpenAI mentioned that this group even analyzed correspondence addressed to a U.S. Senator. On top of that, these actors used OpenAI's models to create marketing materials, basically advertising their services for running fake social media campaigns and recruiting intelligence sources. OpenAI also disrupted operations, probably originating in Russia and Iran. There was also a spam operation from a marketing company in the Philippines, a recruitment scam linked to Cambodia, and a deceptive job campaign that looked like something North Korea might orchestrate. Ben Nimmo, from OpenAI's intelligence team, noted the wide range of tactics and platforms these groups are using. However, he also said these operations were mostly caught early and did not manage to fool large numbers of real people. According to Nimmo, "We didn't generally see these operations getting more engagement because of their use of AI. For these operations, better tools don't necessarily mean better outcomes."
    • Long ago, I was in a networking class on a lab computer. The guy next to sarcastically told me to SHIFT+DELETE the C:\Windows folder. I said that I was sure Windows wouldn't allow such a thing (Windows 2000), and would either totally block the action or give some kind of dire warning. I was so confident that I tried it...not only was I wrong, but it didn't even give the standard "are you sure" warning, just went to town. I pressed cancel as quick as I could, but it was too late, shortly after, the system blue-screened and never booted again. I had to stay late and reinstall Windows for the teacher, but that ended up being a good thing, had great repour with him for the rest of the year, even got to help him get Active Directory setup in his lab.
    • My best decision: SHIFT+DELETE WINDOWS Then Installed Fedora Linux. Now I am a Happy Person
    • I value a game as a whole including graphics. But going backwards in terms of graphics with a game I'm not already invested in (as in something I played and loved in the past and still do) is off-putting. Its a very poor demo trailer if they didn't crank the settings to max that would be ridiculous. Different strokes for different folks i guess, i'm not into slop the trailer and likely game could have been far better, it doesn't it instead looks like it was made on a shoe string budget or with lack of experience. But that could also be down to trying to get it running on low budget/outdated hardware and sacrificing the top end.
    • > Our goal is to ensure that the App Store remains an outstanding opportunity for developers and a safe, trusted experience for our users. There are so many scam apps on the platform that it is hard to believe they are truly interested in having a safe, trusted experience for their users.
  • Recent Achievements

    • One Year In
      survivor303 earned a badge
      One Year In
    • Week One Done
      jbatch earned a badge
      Week One Done
    • First Post
      Yianis earned a badge
      First Post
    • Rookie
      GTRoberts went up a rank
      Rookie
    • First Post
      James courage Tabla earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      419
    2. 2
      +FloatingFatMan
      182
    3. 3
      snowy owl
      181
    4. 4
      ATLien_0
      176
    5. 5
      Xenon
      136
  • Tell a friend

    Love Neowin? Tell a friend!