Getting a simple treeview example to work

M

metaperl

Hello, I'm trying to get the MSDN documentation example of a treeview
to work:
http://msdn2.microsoft.com/en-us/library/system.windows.forms.treeview.aspx

I made the function static and added a call to it in Main():
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1.InitializeTreeView();
Application.Run(new Form1());
}

but I'm getting the error "An object reference is required for the
nonstatic field, method, or property 'treenodeExample.Form1.treeView1'

Here is the Form1 class:
namespace treenodeExample
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be
disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region
// Windows Form Designer Code ommited
#endregion

private System.Windows.Forms.TreeView treeView1;

// Populates a TreeView control with example nodes.
public static void InitializeTreeView()
{

treeView1.BeginUpdate();
treeView1.Nodes.Add("Parent");
treeView1.Nodes[0].Nodes.Add("Child 1");
treeView1.Nodes[0].Nodes.Add("Child 2");
treeView1.Nodes[0].Nodes[1].Nodes.Add("Grandchild");
treeView1.Nodes[0].Nodes[1].Nodes[0].Nodes.Add("Great
Grandchild");
treeView1.EndUpdate();
}
}
}
 
G

GhostInAK

Hello metaperl,

Form1 is a class, and InitializeTreeView() is not static. You can only call
non-static methods on objects (instances of classes) not on classes.

So.. Either instantiate an instance of Form1 first, or move the InitializeTreeView()
call to the Forms load event..

Example of the former:

static void Main() {
Form1 frmMain = new Form1();
frmMain.InitializeTreeView();
Application.Run(frmMain);
}

-Boo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top