Reputation: 1071
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.
Upvotes: 2
Views: 36154
Reputation: 2136
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....
}
Upvotes: 5
Reputation: 6800
Try flushing out the stream just before exiting your button click event using:
stringWriter.Flush();
Upvotes: 0
Reputation: 1249
It would be better for you to use StreamWriter class:
StreamWriter sw = new StreamWriter("test.txt"); // You should include System.IO;
var textBox = control as TextBox;
if (textBox != null)
{
if (string.IsNullOrEmpty(textBox.Text))
{
textBox.Style["visibility"] = "hidden";
}
}
sw.Write(textBox.Text + ",");
Upvotes: 5
Reputation: 4001
The issue is in Submit Code
protected void btnShow_Click(object sender, EventArgs e)
{
System.IO.StreamWriter stringWriter= new System.IO.StreamWriter("c:\\test.txt");
foreach (Control control in Panel1.Controls)
{
var textBox = control as TextBox;
if (textBox != null)
{
if (string.IsNullOrEmpty(textBox.Text))
{
textBox.Style["visibility"] = "hidden";
}
stringWriter.Write( textBox.Text+","); // Write text to textfile.
} // end of if loop
}
Upvotes: 0