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);
}
}

1 comments:

fsugeiger said...

Really good how to on deploying custom code info path forms:http://www.bizsupportonline.net/blog/2009/09/deploy-enable-managed-code-infopath-form-template-sharepoint-library/

Post a Comment