Rogan Rogan - 4 years ago 81
C# Question

Sending data to another page issue

I have a few buttons that send text string data from a textbox to a textblock on another page. Please see code below.

private void button_Click(object sender, RoutedEventArgs e)
Application.Current.Properties["obj1"] = textbox.Text;

private void button2_Click(object sender, RoutedEventArgs e)
Application.Current.Properties["obj2"] = textbox2.Text;

However, it only works when I press all of the buttons, whenever I press only one of them, I run into an error. (Please see below)

An exception of type 'System.NullReferenceException' occurred in
WpfApplication4.exe but was not handled in user code
Additional information: Object reference not set to an instance of an

How do I change it so that if I press only one button, only the information from that textbox is passed over.

The code for the page where the textBlocks are is below.

protected override void OnInitialized(EventArgs e)
textBlock.Text = Application.Current.Properties["obj1"].ToString();
textBlock2.Text = Application.Current.Properties["obj2"].ToString();

Answer Source

The issue that Application.Current.Properties["obj1"] please use null propagation ?. to be sure that in case property is not set you will not try to call ToString() for it

textBlock.Text = Application.Current.Properties["obj1"]?.ToString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download