• 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

    • I have the chance to live where electricity comes only from dams.
    • Which doesn't give them a pass for making the same game with a different skin
    • End of 10: Upgrade to Windows 11 Home or Pro for only $14.97 by Steven Parker Microsoft has been reminding users about the upcoming end of support for Windows 10 that is inbound in less than four months. In the reminder, Microsoft has highlighted ways to deal with the event, covering both scenarios depending on whether your system is eligible for a Windows 11 upgrade or not. If you are in the latter camp, then Microsoft wants you to buy a new Windows 11 PC and that is something the tech giant has repeated time and again, even as recently as this past month in the context of Copilot+ AI PCs. It has also provided some data to back up claims of huge performance and productivity boost, albeit citing a paid study. However, if you are like me and don't plan to buy a CoPilot+ PC, and you have hardware that is eligible for Windows 11 (without bypasses) and if you are locked out of the free upgrade path, you can score a Windows 11 license for very little. Description follows: Upgrade your computing experience with Windows 11 Pro. This cutting-edge operating system boasts a sleek new design and advanced tools to help you work faster and smarter. From creative projects to gaming and beyond, Windows 11 delivers the power and flexibility you need to achieve your goals. With a focus on productivity, the new features are easy to learn and use, enhancing your workflow and efficiency. Whether you're a student, professional, gamer, or creative, Windows 11 Home has everything you need to take your productivity to the next level. New interface. easier on the eyes & easier to use Biometrics login*.Encrypted authentication & advanced antivirus defenses DirectX 12 Ultimate. Play the latest games with graphics that rival reality. DirectX 12 Ultimate comes ready to maximize your hardware* Screen space. Snap layouts, desktops & seamless redocking Widgets. Stay up-to-date with the content you love & the new you care about Microsoft Teams. Stay in touch with friends and family with Microsoft Teams, which can be seamlessly integrated into your taskbar** Wake & lock. Automatically wake up when you approach and lock when you leave Smart App Control. Provides a layer of security by only permitting apps with good reputations to be installed Windows Studio Effects. Designed with Background Blur, Eye Contact, Voice Focus, & Automatic Framing Touchscreen. For a true mouse-less or keyboard-less experience TPM 2.0. Helps prevent unwanted tampering Windows 11 Pro also includes a number of productivity-focused features, such as the ability to snap multiple windows together and create custom layouts, improved voice typing, and a new, more powerful search experience. Personal and professional users will enjoy a modern and secure computing experience, with improved performance and productivity features to help users get more done. Only on Windows 11 Pro If you require enterprise-oriented features for your daily professional tasks, then Windows 11 Pro is a better option. Set up with a local account (only when set up for work or school) Join Active Directory/Azure AD Hyper-V Windows Sandbox Microsoft Remote Desktop BitLocker device encryption Windows Information Protection Mobile device management (MDM) Group Policy Enterprise State Roaming with Azure Assigned Access Dynamic Provisioning Windows Update for Business Kiosk mode Maximum RAM: 2TB Maximum no. of CPUs: 2 Maximum no. of CPU cores: 128 Good to know This license is for Windows 11 only. It is NOT intended to be used for upgrading Microsoft Office (MSO) included in Parallels Pro. However, it will still work with Parallels Pro and allow you to run Windows applications including MSO, but it DOES NOT include an upgrade MSO itself. It is still compatible with Microsoft Office ONLY if you have a separate license for it. Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: desktop Max number of device(s): 1 Version: Windows 11 Pro Updates included Click here to verify Microsoft partnership For example, a Microsoft Windows 11 Pro license normally costs $199, but you can pick it up for just $14.97 for a limited time, that represents a saving of $184. For a full description, specs, and license info, click the link below. Get Windows 11 Home or Pro for just $14.97 See all discounted Neowin Deals on offer. This is a time-limited deal. Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale 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 Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • Looks good!
    • OontZ Angle 3 Coca-Cola Edition Bluetooth Speaker: Worth it at 25% off? by Paul Hill If you are looking for a portable Bluetooth speaker for yourself or for Father’s Day, check out this OontZ Coca-Cola branded Angle 3 Bluetooth speaker. Right now, you can pick it up for just $30, thanks to a recent 25% discount from the previous $40 price tag. Aside from the Coca-Cola branding, this speaker has a range of nifty features including a 100-foot range, a 14-hour battery, IPX5 water resistance, it promises no distortion of sound, and its shape ensures it won’t fall over. What it does (and doesn’t) The Oontz Bluetooth Speaker Angle 3 Coca-Cola Edition is super portable, making it an ideal choice for when you’re traveling. The speaker is just 5.3 inches long and weighs just 10 ounces. The width and height of the speaker are both under three inches and its triangular shape ensures it won’t fall over so you can put it down quickly whenever you’re out and about. According to OontZ, the speaker has 10 watts output that is “surprisingly loud” with “zero distortion” even when you turn it up to the max. These OontZ speakers are crafted by Cambridge Soundworks, a firm that has received critical acclaim since its inception in 1988. The firm is praised for delivering solid sound quality and construction - it makes some of the industry’s best speakers and offers excellent value for the price. As a travel speaker, it’ll probably end up on the beach or next to swimming pools where it can get wet. You don’t need to worry about splashing it though because it comes with IPX5 water resistance meaning it’s splash-proof, suitable for the shower, beaches, or the pool. While it will offer protection against splashes, it shouldn’t be submerged under water. On a single charge, the speaker will last for 14 hours on a single charge and connects to your device using Bluetooth 5.0. It has a good range of 100 feet so it shouldn’t become choppy just because you went into the next room with your phone. Should you buy? This OontZ Coca-Cola Bluetooth speaker is ideal for anyone who wants a great listening experience at home or on the go. It’s also a good choice for anyone looking for good sound on a budget as it’s now $30, which won’t break the bank. The main strengths of the speaker are its excellent value at the discounted price, reliable connectivity, and the good battery life considering its size. The fact that it’s from a reputable brand, Cambridge Soundworks, is also key. The iconic Coca-Cola branding may not be for everybody but it will definitely stand out with that vibrant red color. The IPX5 is also good to protect against splashes but it’s not fully waterproof, so if you need that, this speaker might not be for you. Oontz Bluetooth Speaker Angle 3 Coca-Cola Edition: $29.99 (Amazon US) - MSRP $39.99 / 25% off This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
  • 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
      409
    2. 2
      +FloatingFatMan
      181
    3. 3
      snowy owl
      177
    4. 4
      ATLien_0
      171
    5. 5
      Xenon
      135
  • Tell a friend

    Love Neowin? Tell a friend!