2014-09-06 41 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!"; 
相关问题