locked
Why am I unable to add more children? RRS feed

  • Question

  • User392377 posted

    Hello everyone,

    I am currently making a page to edit a contact. As of now I am making test code to create the functionality before moving to my main app. On the edit contact page there should be an option to add a field (such as add an extra phone number) due to the fact some of the contacts may have more than one phone, email, address, etc..

    The problem I am experiencing is that when I hit a button to dynamically add a field, it only adds one child maximum instead of adding as much as the user would like.

    Here is my .xaml code: <ContentPage.Content> <StackLayout x:Name="Panel"> <Button Text="Add Field" Clicked="AddField"/> <Button Text="Remove Field" Clicked="RemoveField"/> <Entry x:name="newEntry" Placeholder="Origin"/> </StackLayout> </ContentPage.Content> </ContentPage>

    Here is my .cs code

    namespace Test
    {
        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class p2 : ContentPage
        {
            Entry newEntry = new Entry();
            public p2()
            {
                InitializeComponent();
            }
            void AddField(object sender, EventArgs e)
            {
                Panel.Children.Add(newEntry);
            }
            void RemoveField(object sender, EventArgs e)
            {
                Panel.Children.Remove(newEntry);
            }
        }
    }
    

    I have tried using Panel.Children.Add(new Entry()); however when I used this method I was unable to find the line of code required to remove it.

    Thanks in advance for any pointers.

    Wednesday, January 22, 2020 2:59 PM

Answers

  • User89714 posted

    @CupHolder said: I have tried using Panel.Children.Add(new Entry()); however when I used this method I was unable to find the line of code required to remove it.

    Panel.Children.Add(new Entry()); is correct.

    To remove the last Entry, do: panel.Children.RemoveAt(panel.Children.Count - 1);

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Wednesday, January 22, 2020 4:05 PM