1

我有 100 个文本框,我正在尝试将这些文本框中的所有文本写入文本文件,这是我的代码:

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              
    }
}

我在 dev 文件夹中创建了一个名为 test.txt 的文件(我想它应该在哪里)它没有任何错误,但文本文件中没有任何文本。这是正确的方法吗?因为当我尝试调试时, stringWriter 的值将在第一个循环中以 test.txt 开头,在第二个循环中以 test.txttest.txt 开头。

4

4 回答 4

4

当您保持StringWriter打开时,数据不会保存到文件中。在btnShow_Click结束时关闭它:

StringWriter.Close();

或者

using (StringWriter stringwriter=new StringWriter())
{

//here is your code....
}
于 2015-04-18T09:24:31.223 回答
3

最好使用 StreamWriter 类:

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 + ","); 
于 2013-06-25T06:36:26.477 回答
0

问题出在提交代码中

 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              
    }

参考MSDNMSDN

于 2013-06-25T06:34:19.760 回答
0

在退出按钮单击事件之前尝试使用以下命令刷新流:

stringWriter.Flush();
于 2015-02-14T20:24:22.130 回答