Femil Shajin
Femil Shajin

Reputation: 1808

Add a Child to the Parent on Button Click Xamarin.forms

I have been trying to add a Label view to the Stacklayout on Button Click in Android. But It throws Null Pointer exception. Below is what I'm trying to achieve. Can anyone please advice on how to achieve this in xamarin.forms

Xamarin.Forms Code in C#

 StackLayout parent= new StackLayout ();

 Button add= new Button
        {
            HorizontalOptions=LayoutOptions.End,
            BackgroundColor=Xamarin.Forms.Color.White,
            Text="ADD",
            TextColor=Xamarin.Forms.Color.Maroon,
        };

 add.Clicked += OnButtonClicked;
 
 Label firstLabel = new Label
        {
            Text = "Label 1",
            HorizontalOptions = LayoutOptions.StartAndExpand,
            TextColor=Xamarin.Forms.Color.FromHex("#000000")
        };
 parent.Children.Add(add);
 parent.Children.Add(firstLabel );

Adding Label in ButtonClick

 void OnButtonClicked(object sender, EventArgs e)
 {

   Label secondLabel = new Label
        {
            Text = "Label 1",
            HorizontalOptions = LayoutOptions.StartAndExpand,
            TextColor=Xamarin.Forms.Color.FromHex("#000000")
        };
  parent.Children.Add(secondLabel ); 
}

Thanks in Advance

Upvotes: 7

Views: 29486

Answers (1)

Sten Petrov
Sten Petrov

Reputation: 11040

Your code works as is... with one tiny change - make parent a class field so it's referenced from within the OnButtonClicked

Make sure you update the solution packages so you have the latest Xamarin.Forms. Always update the packages on the solution level so do don't get versioning conflicts

This version was tested and works on iOS:

public class LabelPage: ContentPage
    {
        StackLayout parent = null;

        public LabelPage ()
        {
            parent = new StackLayout ();

            Button add = new Button {
                HorizontalOptions = LayoutOptions.End,
                BackgroundColor = Xamarin.Forms.Color.White,
                Text = "ADD",
                TextColor = Xamarin.Forms.Color.Maroon,
            };

            add.Clicked += OnButtonClicked;

            Label firstLabel = new Label {
                Text = "Label 1",
                HorizontalOptions = LayoutOptions.StartAndExpand,
                TextColor = Xamarin.Forms.Color.FromHex ("#000000")
            };
            parent.Children.Add (add);
            parent.Children.Add (firstLabel); 

            Content = parent;
        }

        void OnButtonClicked (object sender, EventArgs e)
        { 
            Label secondLabel = new Label {
                Text = "Label 1",
                HorizontalOptions = LayoutOptions.StartAndExpand,
                TextColor = Xamarin.Forms.Color.FromHex ("#000000")
            };
            parent.Children.Add (secondLabel); 
            //UpdateChildrenLayout ();
        }
    }

Upvotes: 10

Related Questions