Sign in to follow this  
JimboC

Problem with treeView

Recommended Posts

I've got a program with a treeView in it. Everything works correctly except for the fact that the program throws an exception the first time you click on the treeView. Here's the code that's causing the issue:
        private void Add_Device_Mouse_Down(object sender, EventArgs e)
        {
            try
            {                
                TreeView Temp = (TreeView)sender;
                string Test1 = "";
                string Test2 = "";
                                
                Test2 = Temp.SelectedNode.Text;






If I put anything in the program that interrupts it for a second like a message box or something like that, it's fine. If not I'm getting a message that says 'Object reference not set to an instance of an object.' I've tried adding a pause with Thread.Sleep(10000) and I've also tried using the treeView directly (Test2 = treeView1.SelectedNode.Text) but neither has made a difference. Seems anything that doesn't require some kind of user intervention doesn't do the trick. Any ideas what I'm missing? Edit: Using C# 2008

Share this post


Link to post
Share on other sites
What line of code causes the exception to be thrown? I'm guessing that you're getting it on the "Test2 = Temp.SelectedNode.Text" line? SelectedNode is not guaranteed to be non-null...the TreeView can have nothing selected. You should be checking to make sure that it's not null before accessing a property.

Also what event did you hook up this method to? Was it MouseDown? What you probably want is the AfterSelect event, which only gets raised when a node is selected.

Share this post


Link to post
Share on other sites
That not only took care of the exception, but that also cleared up a few other minor glitches that I was causing by using the Mouse_Down event. Thank you so much!

[Edited by - JimboC on September 14, 2009 6:59:11 PM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this