String Writer writing into text file

user2376998 picture user2376998 · Jun 25, 2013 · Viewed 32.1k times · Source

I have 100 textboxes , and i am trying to get all the text from these textboxes to be written into a textfile , this is my code :

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i <= 9; i++)
    {
        for (int j = 0; j <= 9; j++)
        {
            TextBox tb = new TextBox();
            tb.MaxLength = (1);
            tb.Width = Unit.Pixel(40);
            tb.Height = Unit.Pixel(40);
            // giving each textbox a different id  00-99
            tb.ID = i.ToString() + j.ToString();  
            Panel1.Controls.Add(tb);                       
        }
        Literal lc = new Literal();
        lc.Text = "<br />";
        Panel1.Controls.Add(lc);
    }
}

protected void btnShow_Click(object sender, EventArgs e)
{
    StringWriter stringWriter = new StringWriter();
    foreach (Control control in Panel1.Controls)
    {
        var textBox = control as TextBox;   
        if (textBox != null)
        {
            if (string.IsNullOrEmpty(textBox.Text))
            {                
                textBox.Style["visibility"] = "hidden";
            }
            // Write text to textfile.
            stringWriter.Write("test.txt", textBox.Text+","); 
        }  // end of if loop              
    }
}

I have created a file name call test.txt at the dev folder ( I suppose its where it suppose to be) it doesn't have any error , but the text file doesn't have any text in it . Is this the correct way to do it? Because when I tried to debug , the value of stringWriter will begin with test.txt in the first loop and test.txttest.txt in the second loop.

Answer

ako picture ako · Apr 18, 2015

the data will not save to the file when you keep the StringWriter open. at the end of btnShow_Click Close it:

StringWriter.Close();

or

using (StringWriter stringwriter=new StringWriter())
{

//here is your code....
}