2013-06-26 80 views
0

我有一個10×10的文本框(其中100) 我寫這篇文章的代碼寫入到文本文件:寫入文本文件不匹配

foreach (Control control in Panel1.Controls) 
      { 


       var textBox = control as TextBox; 
       if (textBox != null) 
       { 
        if (string.IsNullOrEmpty(textBox.Text)) // ignore this 
        { 

         textBox.Style["visibility"] = "hidden"; 
        } 
        textBox.Enabled = false; 

        if (numberofCommas > 8) 
        { 
         stringWriter.Write(textBox.Text); 
         numberofCommas = 0; 
        } 
        else 
        { 
         stringWriter.Write("," + textBox.Text); 
         numberofCommas++; 
         recordsWritten++; 
        } 

        if (recordsWritten == 10) 
        { 
         stringWriter.WriteLine(); 
         recordsWritten = 0; 
        } 
        else 
        { 

        } 

從上面我想有10行在文本文件中有9個逗號,但是我在文本文件中有9行10個逗號,是我的代碼邏輯錯誤?因爲我一直在看它幾個小時,我仍然無法解決它。對不起,如果我的邏輯不好,我是編程新手。

回答

1

我認爲你應該在最後一步增加recordsWritten

if (numberofCommas > 8) 
{ 
    stringWriter.Write(textBox.Text); 
    numberofCommas = 0; 
    recordsWritten++; 
} 

這裏是一個更好的方式來做到這一點使用LINQ:

var textBoxes = Panel1.Controls.OfType<TextBox>().Select((t, i) => new { TextBox = t, Index = i }).ToList(); 
foreach (var tb in textBoxes) 
{ 
    if (string.IsNullOrEmpty(tb.TextBox.Text)) 
     tb.TextBox.Style["visibility"] = "hidden"; 
    tb.TextBox.Enabled = false; 
} 

foreach (var line in textBoxes.GroupBy(e => e.Index/10) 
         .Select(e => 
          string.Join(", ", 
           e.Select(a => a.TextBox.Text).ToArray()))) 
    stringWriter.WriteLine(line); 
1

我不建議你使用100 TextBox對象,您可以使用DataGridView綁定到10行和10列的DataTable。您仍然可以編輯數據並將其保存到文件中。

嘗試婁代碼

StringWriter stringWriter1 = new StringWriter(); 
    DataTable dataTable1 = new DataTable(); 

    private void Form1_Shown(object sender, EventArgs e) 
    { 
     dataGridView1.AllowUserToAddRows = false; 

     int i; 

     for (i = 0; i < 10; i++) 
     { 
      dataTable1.Columns.Add("Column" + (i + 1), typeof(string)); 
     } 

     for (i = 0; i < 10; i++) 
     { 
      DataRow dataRow1 = dataTable1.NewRow(); 
      dataTable1.Rows.Add(dataRow1); 
     } 

     dataGridView1.DataSource = dataTable1; 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     string rowString = ""; 

     int i,j; 

     for (i = 0; i < 10; i++) 
     { 
      rowString = ""; 

      for (j = 0; j < 10; j++) 
      { 
       if (dataTable1.Rows[i][j].ToString().Contains(",") == true) 
       { 
        //Enclosing the field data inside quotes so that it can 
        //be identified as a single entity. 
        rowString += "\"" + dataTable1.Rows[i][j] + "\"" + ","; 
       } 
       else 
       { 
        rowString += dataTable1.Rows[i][j] + ","; 
       } 
      } 

      rowString = rowString.Substring(0, rowString.Length - 1); 
      stringWriter1.WriteLine(rowString); 
     } 
    } 

你只需要一個DataGridView添加到您的表格。