• 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

    • AMD 25.6.1 driver out with RX 9060 XT support and a lot more FSR 4 games by Pulasthi Ariyasinghe A brand-new hardware launch is happening today for AMD, and to make sure its new GPUs are running properly, a new graphics driver has also landed right alongside it. The AMD Software: Adrenalin Edition 25.6.1 driver lands with support for the RX 9060 XT and the AMD Radeon AI PRO R9700, while also finally updating the number of games that support its AMD FidelityFX Super Resolution 4 upscaling technology. The consumer space-targeted RX 9060 XT graphics card comes in 8GB and 16GB flavors starting at $300 and $350 price points, respectively. Check out our launch coverage for this RDNA 4 GPU for more details here. At the same time, the AMD Radeon AI PRO R9700 comes in for handling professional workloads with a whopping 32GB of VRAM. While support for this card has already arrived with the latest driver, AMD is expecting to ship the product sometime in July 2025. The driver has also added official support for Onimusha 2: Samurai's Destiny Remaster as well, the Capcom-developed action game from last month. As for fixes, AMD has said that it has resolved reversed Quality and Performance selections in the Radeon Boost UI, as well as Le Mans Ultimate performance issues on RX 9070 series GPUs. There are quite a few known issues AMD is still working on: Stutter and lower than expected performance may be observed when using alt-tab and streaming to Discord with multiple monitors. Intermittent application crash or driver timeout may be observed while playing Marvel Spiderman 2 with Ray Tracing enabled on Radeon™ RX 9060 XT. Intermittent application crash may be observed when first launching The Last of Us Part 1 on Radeon™ RX 9060 XT graphics products. Stutter may be observed while playing games with some VR headsets at 80Hz or 90Hz refresh rate on some AMD Radeon™ Graphics Products such as the Radeon™ RX 7000 series. Users experiencing this issue are recommended to change the refresh rate as a temporary workaround. Intermittent system or application crash may be observed while playing Cyberpunk 2077 on some AMD Radeon™ Graphics Products such as the Radeon™ RX 7000 series. Intermittent application crash or driver timeout may be observed while playing Monster Hunter Wilds with Radeon™ Anti-Lag and Instant Replay enabled. Artifacts or corruption may appear while playing Battlefield™ V on Radeon™ RX 7000 series graphics products. Stutter may be observed while playing Call of Duty®: Warzone™ Season 03 ‘Verdansk’ map on some AMD Graphics Products. Stutter and lower than expected performance may be observed while playing 4K resolution YouTube videos in Chromium. Users experiencing this issue are recommended to play videos in full screen as a temporary workaround. Texture flickering or corruption may appear while playing The Elder Scrolls IV: Oblivion Remastered with AMD FidelityFX™ Super Resolution enabled on Radeon™ RX 9070 XT. Users experiencing this issue are recommended to disable AMD FidelityFX™ Super Resolution as a temporary workaround. As for FSR 4, these games are now supported by the popular upscaling tech for gaining more frames: Deadzone: Rogue Rem Survival F1 25 Runescape: Dragonwilds Frostpunk 2 Star Wars Outlaws Legacy: Steel & Sorcery Steel Seed Lords of the Fallen Stellar Blade Planetaries Virtua Fighter 5 R.E.V.O QANGA Wild Assault The complete list of games with FSR 4 support, as well as upcoming implementations, can be found on AMD's support page here. The WHQL-certified AMD Software: Adrenalin Edition 25.6.1 driver can now be downloaded from the AMD Software app as well as the changelog page on its official website here.
    • Download Unruly: Fighting Back when Politics, AI, and Law Upend [...] (worth $18) for free by Steven Parker Claim your complimentary eBook worth $18 for free, before the offer ends on June 17. In Unruly: Fighting Back when Politics, AI, and Law Upend the Rules of Business, co-founder of software company Hence Technologies and former Global Deputy CEO of Eurasia Group, Sean West, delivers a startlingly insightful new take on how politics, technology and law are converging to upend the rules of business, generating dangerous risks and incredible opportunities. West convincingly argues that we must understand all three factors to get leverage over the future – a future filled with eroding rule of law, deepfakes that upend elections and court decisions, government pressure for businesses to be patriotic, robot lobbyists, a flood of automated legal claims pointed directly at your company and much more. Unruly offers detailed, practical advice for how to understand the world ahead, how to be resilient in the face of innumerable and complex challenges, and how to surround your business with the people and technology you need to excel in this environment. Inside the book: A framework for understanding all of the pressures on modern corporations from the convergence of geopolitics, technology and law. Strategies for turning your company's legal department into a source of enduring competitive advantage How to navigate government pressure for nationalism when you have a global footprint Approaches to winning in a world where courts are politicized and the law is increasingly automated, built on interviews with top experts Ways to deal with the backlash to ESG at a company level Perfect for executives, managers, entrepreneurs, founders, and other business leaders, Unruly is also a must-read for general counsels and the advisors who serve them. How to get it Please ensure you read the terms and conditions to claim this offer. Complete and verifiable information is required in order to receive this free offer. If you have previously made use of these free offers, you will not need to re-register. While supplies last! Download Unruly: Fighting Back when Politics, AI, and Law Upend [...] (worth $18) for free Offered by Wiley, view other free resources The below offers are also available for free in exchange for your (work) email: VideoProc Converter AI v7.5 for FREE (worth $78.90) – Expires 6/18 Winxvideo AI V3.0 Lifetime License for PC ($69.95 Value) FREE – Expires 6/8 Aiarty Image Enhancer for PC/Mac ($85 Value) FREE – Expires 6/8 Solutions Architect's Handbook, Third Edition ($42.99 Value) FREE – Expires 6/10 AI and Innovation ($21 Value) FREE – Expires 6/11 Unruly: Fighting Back when Politics, AI, and Law Upend [...] ($18 Value) FREE - Expires 6/17 SQL Essentials For Dummies ($10 Value) FREE – Expires 6/17 Continuous Testing, Quality, Security, and Feedback ($27.99 Value) FREE – Expires 6/18 Macxvideo AI ($39.95 Value) Free for a Limited Time – Expires 6/22 The Ultimate Linux Newbie Guide – Featured Free content Python Notes for Professionals – Featured Free content Learn Linux in 5 Days – Featured Free content Quick Reference Guide for Cybersecurity – Featured Free content We post these because we earn commission on each lead so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin The above deal not doing it for you, but still want to help? Check out the links below. Check out our partner software in the Neowin Store Buy a T-shirt at Neowin's Threadsquad Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: An account at Neowin Deals is required to participate in any deals powered by our affiliate, StackCommerce. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through the branded deals site.
    • AMD RX 9060 XT launches above MSRP and is available to buy now by Sayan Sen At Computex 2025 this year, AMD announced its RX 9060 XT mid-range desktop GPUs. The new graphics card landed in both 8GB and 16GB flavors and targets 1080p as well as light 1440p gaming. The community and some of the media criticized the 8GB VRAM model, but AMD defended the move explaining how the smaller memory buffer is not a cause of worry for the majority. Both the 8 GB and the 16 GB RX 9060 XT are now available for purchase. A new driver is out too with Adrenalin version 25.6.1. However, as always, day one stocks would likely be highly limited, similar to other GPUs or any other product, like the Nintendo Switch 2, that also landed today. Third-party AIB (add in board) vendors like Gigabyte, for example, are selling the 8GB at $329 (SEP is $299) currently on Amazon US, so expect some markup. The technical specifications of the Radeon RX 9060 XT are given below: Specification Value GPU Architecture AMD RDNA™ 4 Core Compute Units 32 Video Memory 16 GB / 8GB GDDR6 Infinity Cache 32 MB Core Boost Clock Up to 3.13 GHz Memory speed/bandwidth 20 Gbps / 320 GB/s AI Performance 821 TOPS (INT4 with sparsity) Raytracing & AI Accelerators 32 3rd Generation Raytracing Accelerators; 64 2nd Generation AI Accelerators PCIe Interface PCIe® 5.0 x16 Display Outputs DisplayPort™ 2.1a, HDMI® 2.1b Total Board Power (TBP) 160W* If you notice, we have an asterisk for the TBP value in the table above. That is because AMD says that it can vary between 150 and 182 watts. Performance-wise, we know the $349 16 GB variant is close to the Nvidia RTX 5060 Ti in rasterization but falls behind in ray tracing. Meanwhile, the 8GB model, priced the same as the GeForce RTX 5060 at $299, should be better, as both 8 Gig and 16 Gig SKUs are identical spec-wise outside of memory capacity. As an Amazon Associate we earn from qualifying purchases.
    • It actually looks decent, although trailers could make the worst nonsense look watchable sometimes. I'm not a fan of the "extended" Aliens universe (Prometheus, Covenant), but I liked Romulus so will definitely give this a shot.
  • Recent Achievements

    • 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
    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      406
    2. 2
      +FloatingFatMan
      181
    3. 3
      snowy owl
      175
    4. 4
      ATLien_0
      170
    5. 5
      Xenon
      135
  • Tell a friend

    Love Neowin? Tell a friend!