Thursday, May 27, 2010

InfoPath 2007 Bind Drop Down List with C#.Net

I have seen several ariticles on how to bind a list in InfoPath 2007 so this isn't anything new but I wanted to share the method that worked best for me. I found it best to make a generic method to bind the list so you can hook it into multiple event handlers. This prevented me from writing the same bit of code twice. If you notice prior to binding the list I clear the list. On a prior post I have posted the code for the ClearListBox method. If you don't clear the list prior to you may end up just appending your values.

private void BindDistrictList(string username, string HomeDistrict)
{
string xpListBox = "/my:myFields/my:listDistrict/my:listDistrictItem";
ClearListBox(xpListBox, Root);

try
{
string data = string.Empty;
using (SqlConnection conn = new SqlConnection(_SqlCon))
{
SqlCommand command = new SqlCommand("IPGetDistrictbyUser", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@UserName", SqlDbType.Char).Value = UserName;
command.Parameters.Add("@hd", SqlDbType.Char).Value = HomeDistrict;
conn.Open();

SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
XmlDocument doc = new XmlDocument();
XmlNode group = doc.CreateElement("listDistrictItem", NamespaceManager.LookupNamespace("my"));
XmlNode field = doc.CreateElement("listDistrictItemName", NamespaceManager.LookupNamespace("my"));
XmlNode node = group.AppendChild(field);
node.InnerText = reader["DistrictName"].ToString();

field = doc.CreateElement("listDistrictItemValue", NamespaceManager.LookupNamespace("my"));
node = group.AppendChild(field);
node.InnerText = reader["DistrictID"].ToString();

doc.AppendChild(group);

MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:listDistrict", NamespaceManager).AppendChild(doc.DocumentElement.CreateNavigator());

}
conn.Close();
}
}
catch (Exception ex)
{
ErrorMessage(ex);
}
}

InfoPath 2007 Clear Databound Drop Down List with C#.Net

Over the past couple weeks I have been working with InfoPath 2007 and cascading drop down list. The issue is once a user decides to go out of the normal flow selection you need to clear the drop down list and re-bind the list. I couldn't find good examples on how to clear a list so I decided to share my code.

Call from your method:
ClearListBox("/my"myFields/my:listLocations/my:listLocationsItem", Root);

Here is the ClearListBox method:
public void ClearListBox(string xp_ListBox, XPathNavigator xNav)
{
//clear list box of items
XPathNodeIterator lstClear = xNav.Select(xp_ListBox, NamespaceManager);
if (lstClear.Count > 0)
{
for (int i = lstClear.Count; i > 0; i--)
{
XPathNavigator reList = MainDataSource.CreateNavigator();
XPathNavigator reListItems = reList.SelectSingleNode(xp_ListBox + "[" + i + "]", NamespaceManager);
reListItems.DeleteSelf();
}
}
}

I am using a Property for Root:
private XPathNavigator Root
{
get
{
return MainDataSource.CreateNavigator();
}
}