开发者

How to convert textbox and label to strings properly

I have this code

FileStream fs = new FileStream("Scores.txt", FileMode.OpenOrCreate, FileAccess.Write);
        StreamWriter sw = new StreamWriter(fs);
        sw.Write("Name: " + name_box.Text + " Time " + label1.Text);
        sw.Close();

which is simple the label1 is assgined to a Timer tick as in the folowing

private void timer1_Tick(object sender, EventArgs e)
    {
        // Format and display the TimeSpan value. 
        TimeSpan ts = stopWatch.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
       label1.Text = elapsedTime;
    }

now when I open the Text File I found the following results

Name: Tony Time 00:00:06.67Text:  Time [System.Windows.Forms.Timer], Interval: 100

which are perfect but what is ( Text: Time [System.Windows.Forms.Timer], Interval: 100) I don't want that to appear in the txt

thanx in 开发者_如何学Pythonadvance


You probably have the following line somewhere else in your code:

label1.Text = timer1.ToString();

You should write-click the word label1 in your code, then click Find All References to see what else you're doing with it.


By the way, instead of creating a stream, you should use File.WriteAllText, like this:

File.WriteAllText("Scores.txt", "Name: " + name_box.Text + " Time " + label1.Text);


You are using FileMode.OpenOrCreate in the constructor. This does not erase the previous contents of the file. I suspect that if you delete the file and then try running your program again, you won't see any of that extra stuff.

I suggest either using FileMode.Create or FileMode.Append. Use the first if you want to overwrite the results, the second if you want to... well, append.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜