Tags

Quite often you will need to get selected values from a Multiple-Selection list box to a field. I haven’t found a way to do in rules but the following code will solve the problem.

Suppose you have a Multiple-Selection List Box named myListBox on an InfoPath form and an after change event to fill a Text Box named myTextBox with the values or display names of the items that were selected in the Multiple-Selection List Box.

Retrieving the values of selected items
You could use the following C# code to retrieve the values that were selected:

        public void field13_Changed(object sender, XmlEventArgs e)
        {
            XPathNavigator root = MainDataSource.CreateNavigator();
            XPathNodeIterator iter = root.Select("//my:myListBox ",
              NamespaceManager);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            while (iter.MoveNext())
            {
                string value = iter.Current.Value;
                sb.Append(value);
                if (sb.Length > 0)
                {
                    sb.Append(";");
                }
            }

            root.SelectSingleNode("//my:myTextBox",
              NamespaceManager).SetValue(sb.ToString());
        }


Retrieving the display names of selected items

If you want to retrieve the Display Names of the items that were selected and you’ve bound the Multiple-Selection List Box to a repeating node either in the Main data source or a secondary data source, you’ll have to do a programmatic lookup to retrieve the Display Names.

You could use the following C# code to retrieve the display names of the items that were selected:

XPathNavigator root = MainDataSource.CreateNavigator();
XPathNodeIterator iter = root.Select("//my:myListBox",
  NamespaceManager);

System.Text.StringBuilder sb = new System.Text.StringBuilder();

while (iter.MoveNext())
{
  string value = iter.Current.Value;

  XPathNavigator secDS = DataSources["Fruits"].CreateNavigator();
  string displayName = secDS.SelectSingleNode(
    "/dfs:myFields/dfs:dataFields/d:Fruits[@ID = '"
    + value + "']/@Name", NamespaceManager).Value;

  sb.Append(displayName);
  sb.Append(";");
}

root.SelectSingleNode("//my:myTextBox",
 NamespaceManager).SetValue(sb.ToString());

where Fruits is a secondary data source, @ID the value of an item, and @Name the display name of an item.

Note: You cannot do a lookup for items if you’ve manually entered them into the list box.

More useful code you can find from http://www.bizsupportonline.net/blog/2009/03/programmatically-retrieve-selected-items-multiple-selection-list-box-infopath/

Advertisements