0
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.

4
  • NullReferenceException happens at runtime, not compile time. In your cs file, where are you setting the .Text property? It is possible that the instance has not yet been created. Commented Jul 13, 2011 at 11:57
  • @billb It's inside the window with the XAML and everything. Commented Jul 13, 2011 at 11:58
  • i am sure that this information is definitely not enough to propose some solution.. if i am not wrong you are trying todo something like this.. TextBlock TextBlock = null; TextBlock.Text = "Text"; Commented Jul 13, 2011 at 11:59
  • @bathineni I really said everything. :S Commented Jul 13, 2011 at 12:13

4 Answers 4

8

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
}
Sign up to request clarification or add additional context in comments.

13 Comments

Please update your question with a little bit of context for this line of code. I have no idea, where you are executing it.
I Edited the question. ("I'm writing this inside a ValueChanged of a Slider.")
@Ken: There is no XAML that defines the TextBlock.
Could you please tell me how to do it? I don't quite understand. sorry. (I just started using WPF for something and just a beginner in C#, so sorry for being stupid)
@Ken: How did you declare that TextBlock variable? How did you put it into your form?
|
1

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";

Comments

1

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 :)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.