Results 1 to 2 of 2
  1. #1
    Join Date
    Jan 2015

    Help Needed C3 Programming

    I have tried and tired and tried to get the output to this code to get the same results of the listbox and all I get is 01234.. and so on. it is a random file and numbers program.

    the code is as follows....

    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 random_files_and_numbers
    public partial class Form1 : Form
    public Form1()

    private void btnGenerateSave_Click(object sender, EventArgs e)

    Random generator = new Random();
    int max = int.Parse(txtAmount.Text);
    StreamWriter outputFile;
    outputFile = File.CreateText("ListNumbers.txt");

    for (int i = 1; i <= max; i++)

    int num = generator.Next(0, 100);
    outputFile.WriteLine(lbrandomNumbers.Items.Add(num ));



    at the outputFile.WriteLine the program does not take the random numbers generated from the code and put it in the TXT File, WHY?

    I don't know and am getting frustrated.

    Please help

  2. #2
    Join Date
    May 2011
    I know this is really old but it was on the front page of posts for some reason so I thought I'd answer it

    outputFile.WriteLine(lbrandomNumbers.Items.Add(num ));

    That line is not doing that you think its doing. I'm not sure what lbrandomNumbers is, but you're adding the random number to that, not the outputFile. The reason you're getting 0, 1, 2, 3, ... output is (and this is my best guess without knowing what lbrandomNumbers is, I assume a list box?), is that the ToString method of that object is being called, and its return value is what is being sent to your outputFile. Looking at the documentation for ListBox, this theory makes sense.

    From there you can see that the ToString method of ListBox returns a string that states the count of items in the list box. So the first time you run through it there will be 0 items in lbrandomNumbers, then 1, then 2, etc.

    What you should do instead is:

    for (int i = 1; i <= max; i++)
    // Store our randomly generated number so that we can do work with it in a bit.
    int num = generator.Next(0, 100);
    // Add the num to the list.
    // Output the num to the file
    Logging the number to output and storing the number as a list item are two entirely different operations and should be written as such.

    Hopefully this helps
    Last edited by frostbytes89; 04-23-2015 at 03:59 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts