2014-09-06 65 views
0

我寫了下面的代碼來創建一個簡單的字典應用程序:如何將一行添加到富文本框?

private void btnDefine_Click(object sender, EventArgs e) 
    { 
     //string word = txtWords.Text; 
     XmlDocument xDoc = new XmlDocument(); 
     try 
     { 
      string [] words = txtWords.Text.Split('\n'); 
      foreach (string word in words){ 
      xDoc.Load("http://www.dictionaryapi.com/api/v1/references/collegiate/xml/" + word + "?key=[KEY]"); 
      txtWords.Text = (xDoc.SelectSingleNode("entry_list/entry/def/dt").InnerText); 

      Clipboard.SetText(txtWords.Text); 
      lblCopied.Text = "Copied to the clipboard!"; 
     } 
     } 
     catch 
     { 
      MessageBox.Show("That is not a word in the dictionary, please try again.", "Word not found in the dictionary", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); 
     } 

    } 
} 

} 這種形式包含了豐富的文本框,其中你可以在進入的話,它會爲您定義的詞。現在,只要我在文本框中輸入一個單詞,就可以獲得定義。但是如果我在文本框中輸入兩個或更多單詞,我會得到列表中最後一個單詞的定義,我該如何使所有定義顯示並以新行顯示。 I.E.,如果我在文本框中輸入三個單詞並按btnDefine,我將得到文本框中所有三個單詞的定義。

回答

0

您可以將它們的定義類似地輸出到它們的輸入方式:分開的行。見String.Join

List<string> definitions = new List<string>(); 
foreach (string word in words) 
{ 
    xDoc.Load("http://www.dictionaryapi.com/api/v1/references/collegiate/xml/" + word + "?key=[KEY]"); 
    string definition = (xDoc.SelectSingleNode("entry_list/entry/def/dt").InnerText); 
    definitions.Add(definition); 
} 
txtWords.Text = String.Join("\n", definitions); 
Clipboard.SetText(txtWords.Text); 
lblCopied.Text = "Copied to the clipboard!";