Search code examples
c#macosxamarinnstextfield

How to get value of a NSTextField which is created programmatically in Xamarin MacOS?


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


Solution

  • You could not convert senderto NSTextField directly.

    Try to change

    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);
    }