1

我的任务从在列表框中显示 100 个随机数开始。这工作正常。接下来,我们使用 StreamWriter 和 StreamReader 将结果写入和读回第二个列表框。在这里,有几件事正在发生。100 行中的每一行都以 ... System.Windows.Forms.ListBox.Items.Count为前缀。

如果你尝试用谷歌搜索这样的短语,MSDN library labrynth 就是所有显示的内容,我没有发现任何适用于此的内容。我被提到 http://www.dotnetperls.com/listbox,但也没有找到解决方案。此外,回读的 100 个条目中的每一个都只是第一个 Random,而不是全部 100 个。我知道这是一个单独的问题。这是_System.Windows.Forms .. 我需要先修复的部分。

我今天请假专心做这件事。时间飞逝,我无处可去。我剖析了我的教科书,疯狂地用谷歌搜索,并在 FaceBook 上发现了一个 .NET 用户组,这也无济于事。..我不知道还能去哪里。

到目前为止,我的代码如下...

/*  Matthew A. May  June 17th. & 22nd POS/409
 * This application simulates the roll of dice 100 times. The output is displayed in 
 * the listBox.  The Results can be saved (written) to a text file.  This txtFile can 
 * then be read back and redisplayed.  **  Some code is derived from...
 * Gaddis, T. (2012). Starting out with Visual C#® 2010 (2nd ed.). Boston, MA: Addison-Wesley.....
 * Page #s' are referenced accordingly throughout where applicable.  * 
 * */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;    //required for the StreamWrite & StreamReader classes for txtFile functions. 

namespace WindowsFormsApplication1
{
    public partial class Main : Form
    {
        private int diceSide1;   // private accessor
        private int diceSide2;   //  Field Variable Declarations.
        private int SUM;         //  SUM = diceSide1 + diceSide2  
        const int Roll_MAX = 100;
        public Main()
        {
            InitializeComponent();
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {
                //GroupBox...
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            /* When the user clicks a Write button, the program will write the sum of the dice for each roll into a sequential data file. 
            the SUM is an int= dye1 + dye 2. SUM cannot be a constant since its' value wil change with each roll. 
             */
        }

        private void btnRollEm(object sender, EventArgs e)
        {
        Random rand = new Random();  //creates new object from Random Class. Gaddis, T. (2012)Chptr5Pg321.

                for (int lineNum = 1; lineNum <= Roll_MAX; lineNum++)
                {
                    diceSide1 = rand.Next(6) + 1;   
                    diceSide2 = rand.Next(6) + 1;
                    SUM = diceSide1 + diceSide2;
                    lstBoxOut.Items.Add ("On roll , " + lineNum + " ,You rolled a " + diceSide1 + " and a "  + diceSide2 + " for a sum of "  + SUM);               
                } //end For-Loop. At this point, output is exactly as expected. 

        } //End btnRollEm

        private void btnWriteToFile(object sender, EventArgs e)
        {          
            StreamWriter rollLog;  //create StreamWriter object reference Variable. 
            rollLog = File.CreateText("Roll Results.txt");  //creating the File. 

            for (int count = 1; count <= 100; count++)
                {
                 rollLog.WriteLine(lstBoxOut);  
                //changing (lstBoxOut) to (count) shows 1-100 vertically.
                //Example Pg.298 & 301, showing where to write to.
                }   //End Write ForLoop

                 rollLog.Close();  //close file after creation.

            MessageBox.Show ("Your results have been successfully Saved to File.");
        }   //reviewing the txtFile, only the 1st line is written 100 times. 

        private void btnReadFile(object sender, EventArgs e)
        {
              //btnRead From File. Hides Main Form, Shows 2nd Form for txtFile OutPut.

             Form2 form2 = new Form2();
             form2.Show(); //Show // StreamReader. Read txt File.
             //// Declare a StreamReader variable.
             //StreamReader rollResults;

             //// Open the file and get a StreamReader object.
             //rollResults = File.OpenText("Roll Results.txt");
        }

        private void lstBoxOut_SelectedIndexChanged_1(object sender, EventArgs e)
        {

        }

        private void btnClear(object sender, EventArgs e)
        {
            lstBoxOut.Items.Clear(); //doesn't work.
        }
        private void btnExit(object sender, EventArgs e)
        {
            this.Close(); // Close the form.
        }
    }    //End Class Declaration
}       //End NameSpace Declaration
4

5 回答 5

2

要写入项目,请将执行写入的行更改为:

rollLog.WriteLine(lstBoxOut.items[count]);

要读回它:

private void btnReadFile(object sender, EventArgs e)
{
    lstBoxOut.Items.Clear();
    foreach (string line in File.ReadLines("Roll Results.txt"))
    {
        lstBoxOut.Items.Add(line);
    }
}

您获得该输出"System.Windows.Forms.ListBox...."的原因是该语句rollLog.WriteLine(lstBoxOut)等效于rollLog.WriteLine(lstBoxOut.ToString()). ToString()方法返回

一个字符串,用于说明控件类型、ListBox 控件中的项计数以及 ListBox 中第一项的 Text 属性(如果计数不为 0)。

于 2013-06-24T20:29:26.820 回答
1

列表框中的每个项目都包含在 Items 集合中。编写这些项目时,您应该遍历项目集合,读取字符串并将其写入磁盘

 using(StreamWriter rollLog = new StreamWriter("Roll Results.txt"))  
 {
    for (int count = 0; count < lstBoxOut.Items.Count; count++)
    {
        rollLog.WriteLine(lstBoxOut.Items[count].ToString());  
    }   
 }

还要注意循环从索引 0 开始并在 Items.Count - 1 结束,因为在 NET 中,数组是从零开始的。using 语句也非常有用,因为在出​​现错误(异常)的情况下,它可以确保正确关闭文件

读操作类似

 using(StreamReader rollLog = new StreamReader("Roll Results.txt"))  
 {

    while (rollLog.Peek() >= 0)
    {
        lstBoxOut.Items.Add(rollLog.ReadLine());  
    }   
 }
于 2013-06-24T20:29:35.280 回答
0

在“写入文件”方法中,您指定以下内容:

rollLog.WriteLine(lstBoxOut);

由于之前的一些代码,我将假设 lstBoxOut 是一个 ListBox 项,特别是:

lstBoxOut.Items.Add ("On roll , " + lineNum + " ,You rolled a " + diceSide1 + " and a "  + diceSide2 + " for a sum of "  + SUM);

话虽如此,这不是您从列表框中获取项目的方式。考虑使用

lstBoxOut.Items[count].ToString()

在 WriteLine 命令中,或者为了更好的实践,使用 foreach 循环而不是 for 循环。

于 2013-06-24T20:31:21.323 回答
0

Please modify your code as per follows

 private void btnWriteToFile(object sender, EventArgs e)
    {          
        StreamWriter rollLog;  //create StreamWriter object reference Variable. 
        rollLog = File.CreateText("Roll Results.txt");  //creating the File. 

        for (int count = 0; count <lstBoxOut.Items.Count;  count++)
            {
             rollLog.WriteLine(Convert.ToString(lstBoxOut.Items[count]));  
            //changing (lstBoxOut) to (count) shows 1-100 vertically.
            //Example Pg.298 & 301, showing where to write to.
            }   //End Write ForLoop

             rollLog.Close();  //close file after creation.

        MessageBox.Show ("Your results have been successfully Saved to File.");
    }   //reviewing the txtFile, only the 1st line is written 100 times. 
于 2013-06-24T20:30:02.777 回答
0
for (int count = 1; count <= 100; count++)
{
    rollLog.WriteLine(lstBoxOut); 
}

This is probably the source of your problem. For each iteration of the loop, you're writing the same thing to the file (hence the 100 identical lines). A big clue to seeing this, by the way, is that most of the time (not always) when you have a loop variable ('count' in this case) you should be using that variable in the body of your loop somewhere.

Next up, the odd-looking "System.Windows.Forms.ListBox.Items.Count" data. This is happening because of what you're writing to that file. You're writing "lstBoxOut", which is the listbox itself, rather than the contents. By default, the majority of WPF types will just convert to the name of the type when you do this. What you're probably wanting to write is something like this:

for (int count = 1; count <= 100; count++)
{
    rollLog.WriteLine(lstBoxOut.Items[count]); 
}
于 2013-06-24T20:30:33.753 回答