当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - ListBox displays "System.Windows.Forms.ListBox.Items.Count..."

问题描述:

My assignment started with displaying 100 Random numbers in a listBox. This works fine. Next, we use StreamWriter & StreamReader to write and read back the results to a 2nd listBox. Here, a couple of things are happening. Each of the 100 lines is prefixed with ...

System.Windows.Forms.ListBox.Items.Count.

If you try to Google such a phrase, the MSDN library labrynth is all that shows, and I've found nothing that applies to this. I was referred to http://www.dotnetperls.com/listbox , but found no solution there either. Also, each of the 100 entries read back is only the first Random, not all 100. I know that's a separate issue. It's the_System.Windows.Forms.. part I need to fix first.

I called off work today to concentrate on this. Time is flying and I'm getting nowhere. I've dissected my textbook, Googled like mad and found a .NET user group on FaceBook that is of no assistance either. ..I don't know where else to go.

My code thus far is as follows...

/* 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

网友答案:

To write the items, change the line that does the write to:

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

To read it back in:

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

The reason you're getting that output "System.Windows.Forms.ListBox...." is because the statement rollLog.WriteLine(lstBoxOut) is equivalent to rollLog.WriteLine(lstBoxOut.ToString()). The ToString() method returns

A string that states the control type, the count of items in the ListBox control, and the Text property of the first item in the ListBox, if the count is not 0.

网友答案:

Every item in the listbox is contained in the Items collection. When writing these items you should loop over the items collection, read the string and write it to disk

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

Notice also the loop start at index 0 and ends at Items.Count - 1 because in NET the array are zero based. The using statement is also very useful because in case of errors (exceptions) it ensures the correct closing of the file

The reading operation is similar

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

    while (rollLog.Peek() >= 0)
    {
        lstBoxOut.Items.Add(rollLog.ReadLine());  
    }   
 }
网友答案:

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. 
网友答案:
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]); 
}
网友答案:

In your "Write to File" method, you specify the following:

rollLog.WriteLine(lstBoxOut);

I'm going to assume that lstBoxOut is a ListBox item because of some previous code, notably:

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

That being said, that's not how you obtain the items from a listbox. Consider using

lstBoxOut.Items[count].ToString()

within the WriteLine command or, for better practice, use a foreach loop instead of a for loop.

分享给朋友:
您可能感兴趣的文章:
随机阅读: