Search code examples
c#xpathinfopath

InfoPath adding a new row programmatically to end of list


I am currently helping a client creating a form with InfoPath and Im having some problems getting my lists to act like I want.

Whenever I add a new element to a list (Repeating Section) it ends up on top of the list in the view, and I want it to be added to the bottom. My client wants a custom button to trigger the addition of the element and not use the "add element" text that InfoPath provides.

Here is an example to better explain my problem:

enter image description here

When a user writes in a something in the input field, I want it to be added to the list in the repeating section. Here is a sample code:

private XPathNavigator GetField(string xPath)
{
    return MainDataSource.CreateNavigator()
                         .SelectSingleNode(xPath, NamespaceManager);
}

public void CTRL10_5_Clicked(object sender, ClickedEventArgs e)
{
    string xPathToList = "/my:myFields/my:group5/my:group6/my:group7";
    string xPathToInput = "/my:myFields/my:group5/my:field2";
    string xPathToListElement = xPathToList + "/my:field3";

    //Creates a new row
    XPathNavigator list = GetField(xPathToList);
    XPathNavigator newRow = list.Clone();
    newRow.InsertAfter(list);

    //Sets values on the new row
    XPathNavigator input = GetField(xPathToInput);
    XPathNavigator nameField = GetField(xPathToListElement);
    nameField.SetValue(input.Value);
    input.SetValue("");
}

When I add a new element to the list it is added to the top of the list, not the bottom.. enter image description here

Any suggestions?


Solution

  • The solution I made it work with was getting the last ( [last()] ) element in the list in the XPath expression, and adding the element to after the specified element.

    private XPathNavigator GetField(string xPath)
    {
         return MainDataSource.CreateNavigator()
                              .SelectSingleNode(xPath, NamespaceManager);
    }
    
    public void CTRL10_5_Clicked(object sender, ClickedEventArgs e)
    {
        string xPathToList = "/my:myFields/my:group5/my:group6/my:group7[last()]";
        string xPathToInput = "/my:myFields/my:group5/my:field2";
        string xPathToListElement = xPathToList + "/my:field3";
    
        //Creates a new row
        XPathNavigator list = GetField(xPathToList);
        XPathNavigator newRow = list.Clone();
        newRow.InsertAfter(list);
    
        //Sets values on the new row
        XPathNavigator input = GetField(xPathToInput);
        XPathNavigator nameField = GetField(xPathToListElement);
        nameField.SetValue(input.Value);
        input.SetValue("");
    }