0

これは私のコードです:

   protected void btnShow_Click(object sender, EventArgs e)
   {
      System.IO.StreamWriter stringWriter = new System.IO.StreamWriter(Server.MapPath(@"~/Puzzle/puzzle.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+",");
           }  // end of if loop              
      }
      stringWriter.Close();        
   }// end of button         

たとえば、私のテキスト ファイルは次のようになります。

,S,U,P,,,,,,,,

テキストファイルで次のようにしたい:

,S,U,P,
,,,,
,,,,

4番目のコンマを打った後、次の行に移動したい。
どうすればいいのですか?

4

1 に答える 1

4

4番目のコンマを打った後、次の行に移動したい. どうすればいいのですか?

これまでに書き込んだコンマの数を追跡し、カウンターが 4 に達したら、それを 0 にリセットしてファイルに新しい行を追加するだけです。

protected void btnShow_Click(object sender, EventArgs e)
{
    using (var writer = new StreamWriter(Server.MapPath(@"~/Puzzle/puzzle.txt")))
    {
        int recordsWritten = 0;
        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 + ",");

                recordsWritten++;
                if (recordsWritten == 4)
                {
                    stringWriter.WriteLine();
                    recordsWritten = 0;
                }
            }
        }
    }
}
于 2013-06-25T07:09:41.610 に答える