Event Handlers modifying UI.

 public class MainActivity : Activity
{
    int count = 1;
    Button button;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
        Button button = FindViewById<Button>(Resource.Id.MyButton);
        button.Click += button_Click;
    }

    void button_Click(object sender, EventArgs e)
    {
        button.Text = string.Format("{0} clicks!", count++);
    }
}

I get this error: "Object reference not set to an instance of an object" inside the button_Click Method. Could somebody explain me why?

Posts

  • CheesebaronCheesebaron DKInsider, University mod

    That code should not compile...

  • Gonzalo.2718Gonzalo.2718 USMember

    Hmm. So how can I use an event handler (not a delegate) to modify the buttons, TextViews's,EditText's, etc of my AXML?

  • TomOpgenorthTomOpgenorth CAXamarin Team Xamurai

    Inside your OnCreate you have a local declaration for button which is overriding the class variable. Here is what your OnCreate should look like:

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
        button = FindViewById<Button>(Resource.Id.MyButton);
        button.Click += button_Click;
    }
    
  • JoeMankeJoeManke USMember ✭✭✭✭✭

    Alternatively, the sender of the click event is the button, so you could set its text like this:

    void button_Click(object sender, EventArgs e)
    {
        (sender as Button).Text = string.Format("{0} clicks!", count++);
    }
    
  • Gonzalo.2718Gonzalo.2718 USMember

    Thanks! It worked! (My mistake was really stupid btw)

Sign In or Register to comment.