Introduction
This Article is about the FormState of InfoPath 2007.
InfoPath 2007 has the new property called “FormState”, this could be used to store the state values. In previous version of InfoPath, to store the state values, you would have used hidden variables. This property will reduce or avoid the use of hidden variables.
About FormState
FormState is an IDictionary object, which holds the user-defined state values, which were defined in the variable declaration section i.e., before the InternalStartup() of FormCode class.
Using FormState, user-defined state variables can be accessed from code running in forms opened in Microsoft Office InfoPath 2007 or in a Web browser. It is also possible to store the state value in global member variable only when you use InfoPath client, but this will not work in Web browser. Design Checker of InfoPath will throw an error to use the FormState instead of global member variables.
Example
Following example shows the design pattern for creating the user defined state variable in declaration section of FormCode class.
///
///
private int count
{
get
{
// If the state variable “count” is not initialized then
// return 0; return the count otherwise.
if (FormState["_count"] != null)
{
return (int)FormState["_count"];
}
else
{
return 0;
}
}
set
{
FormState["_count"] = value;
}
}
In the above example, “count” is a private property, which can be accessed only within the FormCode class. FormState holds the values as “Key, Value” pair, here the Key is _count. If the _count is not initialized, zero will be returned; otherwise the value stored in the _count will be returned.
It is also possible to store different types of objects in FormState. For example, I have a list of holidays for a particular location, which is in the Holiday Table in the database. I have to use this list in different methods in my FormCode class and also each time I do not want to fetch this list from database.
For the above scenario, we can create a HashTable (which is also inherited from IDictionary) to store the holiday list from the database in the Load event of the Form. Store this in the FormState Dictionary.
///
/// Get or Set the Holiday List
///
private Hashtable holidayList
{
get
{
return (Hashtable)FormState["_holidayList"];
}
set
{
FormState["_holidayList"] = value;
}
}
Now, this property “holidayList” can be used in different methods in the FormCode class.
Conclusion
FormState will be very useful to store the user-defined state data and access the same in InfoPath 2007 and also in Web browser.