• 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

    • What? Every single app I've installed from the Microsoft Store comes from its intended developer and works perfectly fine. What apps do you install?
    • Microsoft Store is such a weird place filled with so much absolute garbage and with reputable apps that somehow come from questionable sources. Like, the app name is known, the images back it up but the publisher is just some weird name that's not mentioned for the apps we know.
    • NTLite 2025.06.10459 is out.
    • Wireshark 4.4.7 by Razvan Serea  Wireshark is a network packet analyzer. A network packet analyzer will try to capture network packets and tries to display that packet data as detailed as possible. You could think of a network packet analyzer as a measuring device used to examine what's going on inside a network cable, just like a voltmeter is used by an electrician to examine what's going on inside an electric cable (but at a higher level, of course). In the past, such tools were either very expensive, proprietary, or both. However, with the advent of Wireshark, all that has changed. Wireshark is perhaps one of the best open source packet analyzers available today. Deep inspection of hundreds of protocols, with more being added all the time Live capture and offline analysis Standard three-pane packet browser Multi-platform: Runs on Windows, Linux, OS X, Solaris, FreeBSD, NetBSD, and many others Captured network data can be browsed via a GUI, or via the TTY-mode TShark utility The most powerful display filters in the industry Rich VoIP analysis Read/write many different capture file formats Capture files compressed with gzip can be decompressed on the fly Live data can be read from Ethernet, IEEE 802.11, PPP/HDLC, ATM, Bluetooth, USB, Token Ring, Frame Relay, FDDI, and others (depending on your platfrom) Decryption support for many protocols, including IPsec, ISAKMP, Kerberos, SNMPv3, SSL/TLS, WEP, and WPA/WPA2 Coloring rules can be applied to the packet list for quick, intuitive analysis Output can be exported to XML, PostScript®, CSV, or plain text Wireshark 4.4.7 changelog: The following vulnerabilities have been fixed wnpa-sec-2025-02 Dissection engine crash. Issue 20509. CVE-2025-5601. The following bugs have been fixed Wireshark does not correctly decode LIN "go to sleep" in TECMP and CMP. Issue 20463. Dissector bug, Protocol CIGI. Issue 20496. Green power packets are not dissected when proto_version == ZBEE_VERSION_GREEN_POWER. Issue 20497. Packet diagrams misalign or drop bitfields. Issue 20507. Corruption when setting heuristic dissector table UI name from Lua. Issue 20523. LDAP dissector incorrectly displays filters with singleton "&" Issue 20527. WebSocket per-message compression extentions: fail to decompress server messages (from the 2nd) due to parameter handling. Issue 20531. The LL_PERIODIC_SYNC_WR_IND packet is not properly dissected (packet-btle.c) Issue 20554. Updated Protocol Support AT, BT LE LL, CIGI, genl, LDAP, LIN, Logcat Text, net_dm, netfilter, nvme, SSH, TCPCL, TLS, WebSocket, ZigBee, and ZigBee ZCL Download: Wireshark 4.4.7 | 83.2 MB (Open Source) Download: Portable Wireshark 4.4.7 | ARM64 Installer View: Wireshark Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Snapchat finally has a watchOS app, a decade after the Apple Watch launched by David Uzondu Snap has announced that Snapchat is finally hopping onto Apple Watch, something many users have probably been waiting for. This new app lets you easily preview an incoming message right on your wrist and then fire back a reply without ever needing to grab your iPhone. For those quick responses, you have options: you can tap out a message on the keyboard, use Scribble to draw letters, dictate your reply, or just send a fitting emoji. Snap says it's trying to make Snapchat easier to use on all the different devices people have in their lives. It's already seen people using Snapchat on tablets and the web, so bringing it to wearables like the Apple Watch feels like the next natural move. That marks a big change from back in 2015 when the Apple Watch first launched. At the time, Snap took a more cautious "wait and see" approach, wanting to see if people actually used smartwatches before building an app. New app launches are not always perfect. It is still early days for the watchOS app, as some users on Reddit have reported the app being stuck on the loading screen. Hopefully, Snap will address these initial teething problems quickly. This expansion to Apple Watch comes after the company abandoned its widely criticized three-tab app redesign following a notable drop in its North American daily active users and significant negative feedback. That redesign, introduced back in September 2024, was meant to simplify things but ended up frustrating many, leading Snap to reverse course after about seven months and work on a refined five-tab layout. Meanwhile, Android smartwatch users with Wear OS are still in a different boat, as there is no official, dedicated Snapchat app for that platform yet. They can typically only receive notifications, and attempts to sideload the full Android app often result in a clunky experience.
  • Recent Achievements

    • Week One Done
      CHUNWEI earned a badge
      Week One Done
    • 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
  • Popular Contributors

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

    Love Neowin? Tell a friend!