Programmatically add lines of text to a Rich Text Box field on an InfoPath form using C# code
Use C# code to add DIV elements to apply line-breaks between lines of text in a rich text box field on an InfoPath form.
Problem
You have a Rich Text Box control on an InfoPath form template and you would like to programmatically add lines of text to the Rich Text Box including line-breaks, that is, you want each line of text to appear on a separate line.
Solution
Use <div> elements to apply line-breaks between lines of text in a Rich Text Box on an InfoPath form.
Before You Begin
You should be able to do the following:
- How to programmatically get or set the XHTML code of a Rich Text field in InfoPath 2007
- How to get HTML tags to appear as HTML and not as plain text in a Rich Text Box
Discussion
If you have a Rich Text Box control named rtfField on an InfoPath form template, you can put the following C# code in the Clicked event handler of a Button control to programmatically add two lines of text to the Rich Text Box field on the InfoPath form:
XPathNavigator nav = MainDataSource.CreateNavigator();
XPathNavigator rtfNav = nav.SelectSingleNode("//my:rtfField", NamespaceManager);
using (XmlWriter rtfWriter = rtfNav.AppendChild())
{
rtfWriter.WriteStartElement("div", "http://www.w3.org/1999/xhtml");
rtfWriter.WriteString("Line 1");
rtfWriter.WriteEndElement();
rtfWriter.WriteStartElement("div", "http://www.w3.org/1999/xhtml");
rtfWriter.WriteString("Line 2");
rtfWriter.WriteEndElement();
rtfWriter.Close();
}
Or you can use the following C# code, which uses XmlDocument objects to add elements to rtfField.
XPathNavigator nav = MainDataSource.CreateNavigator();
XPathNavigator rtfNav = nav.SelectSingleNode("//my:rtfField", NamespaceManager);
XmlDocument doc = new XmlDocument();
XmlElement elm = doc.CreateElement("div", "http://www.w3.org/1999/xhtml");
elm.InnerText = "Line 1";
doc.AppendChild(elm);
rtfNav.AppendChild(doc.DocumentElement.CreateNavigator());
doc = new XmlDocument();
elm = doc.CreateElement("div", "http://www.w3.org/1999/xhtml");
elm.InnerText = "Line 2";
doc.AppendChild(elm);
rtfNav.AppendChild(doc.DocumentElement.CreateNavigator());
Now when you click the button, the text lines will be added with a line-break between them.
Related InfoPath Articles:
