2015-05-29 20 views
0

我有一個winform按鈕的代碼,它可以從文本文件生成一個隨機行或者讓我爲這個文件添加一個新句子。 (取決於哪個單選按鈕處於活動狀態)。通過同一個文本框中的相同按鈕生成,添加,編輯和刪除

private void button1_Click(object sender, EventArgs e) 
     { 

      string FilePath = @"C:\file.txt"; 

if (radioButtonNew.Checked) 
     { 
      string[] Lines = File.ReadAllLines(FilePath); 
      Random rand = new Random(); 
      string SentNew = Lines[rand.Next(0, Lines.Length)]; 
      TextBox.Text = SentNew; 
     } 

    else 
     { 
     File.AppendAllText(FilePath, TextBox.Text + environment.NewLine); 
     MessageBox.Show("Value added"); 
     } 

但是例如我不喜歡隨機的結果之一,不僅想再添一個.. 而是糾正生成的結果,然後再按下一個按鈕,更改線路。

或者我想從文件中刪除一條生成的行。只需添加兩個單選按鈕,可以在相同的按鈕和文本框中完成操作嗎?

我不知道該怎麼做,你能幫忙嗎?我的目標是隨機生成,添加我自己的(我擁有的),編輯和刪除生成的行。問題是 - 我不太清楚如何告訴程序編輯或刪除它剛剛生成的文本框中的隨機行。

+0

當然可以。在類級別(單擊事件之外)存儲'rand.Next()'生成的** Index **值,以便知道該行從哪裏來。現在讀取文件並將其放入列表而不是陣列。這將允許您編輯該條目**和/或**將其從列表<>中刪除。要更新文件,使用'File.WriteAllLines()'。 –

回答

1

快速的什麼我在評論上述(未經測試)例如:

private Random rand = new Random(); 

    private int Index = -1; 
    private List<String> Lines = new List<string>(); 

    private void button1_Click(object sender, EventArgs e) 
    { 
     string FilePath = @"C:\file.txt"; 

     if (radioButtonNew.Checked) 
     { 
      Lines = new List<String>(File.ReadAllLines(FilePath)); 
      Index = rand.Next(0, Lines.Count); 
      label1.Text = "Index: " + Index.ToString(); 
      TextBox.Text = Lines[Index]; 
     } 
     else if (radioButtonAppend.Checked) 
     { 
      File.AppendAllText(FilePath, TextBox.Text + Environment.NewLine); 
      Lines = new List<String>(File.ReadAllLines(FilePath)); 
      Index = Lines.Count - 1; 
      label1.Text = "Index: " + Index.ToString(); 
      MessageBox.Show("Line added"); 
     } 
     else if (radioButtonModify.Checked) 
     { 
      if (Index >= 0 && Index < Lines.Count) 
      { 
       Lines[Index] = TextBox.Text; 
       File.WriteAllLines(FilePath, Lines); 
       MessageBox.Show("Line Modified"); 
      } 
      else 
      { 
       MessageBox.Show("No Line Selected"); 
      } 
     } 
     else if (radioButtonDelete.Checked) 
     { 
      if (Index >= 0 && Index < Lines.Count) 
      { 
       Lines.RemoveAt(Index); 
       File.WriteAllLines(FilePath, Lines); 
       Index = -1; 
       label1.Text = "Index: " + Index.ToString(); 
       MessageBox.Show("Line Deleted"); 
      } 
      else 
      { 
       MessageBox.Show("No Line Selected"); 
      } 
     } 
    } 
+0

非常感謝,邁克!我會研究你的例子。 –

相關問題