Forum Xamarin.Mac

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

How to get value of a NSTextField which is created programmatically

codergcoderg Member ✭✭

I get "Object reference not set to an instance of an object" error while trying to print the "StringValue" value of my Texfield created programmatically?

NSTextField[] t = new NSTextField[1];
public override void ViewDidLoad()
{
base.ViewDidLoad();

    t[0] = new NSTextField();
    t[0].Frame = new CoreGraphics.CGRect(20, 1, 200, 20);
    t[0].Tag = 0;
    t[0].Identifier = "0";
    t[0].StringValue = "yahoo";
    t[0].Bordered = true;
    t[0].Changed += new EventHandler(testt);
    this.myNSBox.AddSubview(t[0]);

}

public void testt(Object sender, EventArgs e) {
NSTextField check = sender as NSTextField;
//var check = sender as NSTextField; this is also not working
Console.WriteLine(check.StringValue);
}

System.NullReferenceException: Object reference not set to an instance of an object
at myProject.ViewController.testt (System.Object sender, System.EventArgs e) [0x00008] in
/path to my folder /ViewController.cs:125
at AppKit.NSTextField+_NSTextFieldDelegate.Changed (Foundation.NSNotification notification) [0x00011] in /Library/Frameworks/Xamarin.Mac.framework/Versions/6.10.0.17/src/Xamarin.Mac/NSTextField.g.cs:1093
at at (wrapper managed-to-native) AppKit.NSApplication.NSApplicationMain(int,string[])
at AppKit.NSApplication.Main (System.String[] args) [0x00040] in /Library/Frameworks/Xamarin.Mac.framework/Versions/6.10.0.17/src/Xamarin.Mac/AppKit/NSApplication.cs:100
at myProject.MainClass.Main (System.String[] args) [0x00007] in
/path to my folder /Main.cs:57

Answers

  • ChrisHamonsChrisHamons USForum Administrator, Xamarin Team Xamurai

    I'd yet again suggest fully reading the FAQ: https://forums.xamarin.com/discussion/31680/welcome-to-the-xamarin-mac-forums-and-faq#latest

    I suspect that your Views are not created by ViewDidLoad, as they are defined in a nib/storyboard that hasn't inflated yet. Choose another lifecycle override, such as view added to superview tree or about to show.

  • codergcoderg Member ✭✭

    RESOLVED:

    changed:

    public void testt(Object sender, EventArgs e)
    {
    NSTextField check = sender as NSTextField;
    //var check = sender as NSTextField; this is also not working
    Console.WriteLine(check.StringValue);
    }
    to

    public void testt(Object sender, EventArgs e)
    {
    NSNotification notification = sender as NSNotification;
    NSTextField check = notification.Object as NSTextField;
    Console.WriteLine(check.StringValue);
    }

Sign In or Register to comment.