MasterMastic
MasterMastic

Reputation: 21306

Setting WPF's Textblock.Text property throws NullReferenceException

textBlock.Text = "Text";

This is my code, and it shows no errors. but when I run it, I get a NullReferenceException

Object reference not set to an instance of an object.

This statement is inside a ValueChanged event of a Slider, should it matter.

Upvotes: 0

Views: 7555

Answers (4)

LittleTiger
LittleTiger

Reputation: 332

The "valuechanged" event happens already inside the InitializeComponent() call. So what you might need to do in your algorithm is check if the textbox == null (and don't do anything if this is true!..).

Had the same issue, but already had this thread open so.. It's late, but hopefully it'll help someone else soon :)

Upvotes: 1

Dummy01
Dummy01

Reputation: 1995

If your TextBlock definition is other than this <TextBlock x:Name="TextBlock"/> then your program does not compile at all.

But if it is like that then just make sure InitializeComponent() in the constructor of your window is executed before accessing any childs.

Upvotes: 0

emp
emp

Reputation: 5075

If this is at compile time and not even at runtime it seems like your reference to the Textblock object isnt' right.

Is this exactly your code? Try the following in your XAML:

<TextBlock x:Name="myTextBlock" />

And in your CS File:

myTextBlock.Text = "Text";

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

I assume this code is in your constructor. Make sure InitializeComponents is called before you execute this line:

public YourWindow()
{
    TextBlock.Text = "Text"; // <- bad
    InitializeComponents();
    TextBlock.Text = "Text"; // <- good
}

Upvotes: 8

Related Questions