Retrieve an InfoPath form from SQL Server and display it in an InfoPath FormControl
Use code to retrieve the XML of an InfoPath form from SQL Server 2005, convert the InfoPath form into a MemoryStream object, and load this object into an InfoPath FormControl on a Windows Forms application.
Problem
You saved InfoPath forms in an XML field in SQL Server 2005 and would now like to retrieve one of those forms and display it within an InfoPath FormControl in a Windows Forms application.
Solution
Use C# code to retrieve the XML of the InfoPath form from SQL Server 2005, convert the XML of the InfoPath form into a MemoryStream object, and load this object into an InfoPath FormControl on a Windows Forms application.
Discussion
You can accomplish this functionality as follows:
- Open Microsoft Visual Studio 2005 and create a new Windows Application project.
- Add an InfoPath FormControl to the main Windows Form of the application.
- Double-click on the surface of the main Windows Form to add a Load event handler.
- Add using statements for System.Data.SqlClient, System.Text,
System.IO, and put the following code in the Load event handler of the Windows Form:
string data = string.Empty;
using (SqlConnection conn = new SqlConnection("Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=True"))
{
// Open a connection to the database conn.Open();
// Retrieve the XML data for an InfoPath form that has an ID equal to 1 SqlCommand cmd = new SqlCommand(@"SELECT Form FROM IPForms WHERE ID = 1", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
data = reader.GetString(0);
}
// Close the connection to the database conn.Close();
}
// Convert the XML data for the InfoPath form into a byte array
byte[] bytes = Encoding.UTF8.GetBytes(data);
using (MemoryStream memStream = new MemoryStream())
{
// Load the byte array into the memory stream memStream.Write(bytes, 0, bytes.Length);
// Load the memory stream into the FormControl
formControl1.Open(memStream);
// Close the memory stream
memStream.Close();
} - Build your project and test the Windows application.
Now whenever you open the Windows Forms application, the InfoPath form with an ID equal to 1 in the SQL Server database will be retrieved from the SQL Server database and loaded into the InfoPath FormControl and displayed on the Windows Forms application.
Related InfoPath Articles:
