2013-06-25 184 views
1

我有100個文本框,我試圖讓所有這些文本框將被寫入一個文本文件的文本,這是我的代碼:字符串writer寫入文本文件

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開頭。

+0

哪裏是你的文件中定義在這裏 – MDMalik

+0

很抱歉,但我不知道是什麼意思ü你 – user2376998

+0

輸出文件的路徑沒有定義 – MDMalik

回答

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

+0

嗨,感謝您的回覆,文本文件仍然是空的。我不明白Streamwriter是如何工作的 – user2376998

2

這將是更好地爲您使用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 + ","); 
0

嘗試之前沖洗出來的流退出您的按鈕點擊事件使用:

stringWriter.Flush(); 
3

當您保持打開StringWriter時,數據不會保存到文件中。 在末btnShow_Click關閉它:

StringWriter.Close(); 

using (StringWriter stringwriter=new StringWriter()) 
{ 

//here is your code.... 
}