Wrox Programmer Forums
Go Back   Wrox Programmer Forums > C# and C > C# 2005 > C# 2005
C# 2005 For discussion of Visual C# 2005.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the C# 2005 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
Old July 2nd, 2007, 12:56 AM
Registered User
Join Date: Jul 2007
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default Altering a listbox from another form

I have a listbox in Form1. In Form2 I try to add an item to that listbox in Form1.

The code in question from Form2:
private void button1_Click(object sender, EventArgs e)

The problem: I get "An object reference is required for the nonstatic field, method, or property 'myprojext.Form1.listbox1'" error.

Any ideas on what is wrong?
Old July 9th, 2007, 06:12 AM
Authorized User
Join Date: Dec 2004
Posts: 68
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to DZukiewicz

The problem is that the ListBox control only exists when Form1 is created. Doing Form1.listBox1 doesn't work because the listBox isn't marked as static.

The best way to do this is to add a property to Form2, called Form1Ref and then give it a reference to the Form1 before you show it:

//In Form2
private Form1 form1Ref;

public Form1 Form1Ref 
     get { return form1Ref; }
     set { form1Ref = value; }
//In Form1
private void ShowForm2()
     Form2 newForm = new Form2();
     newForm.Form1Ref = this;

Now you can call this.Form1Ref.listBox1 to get access to it.



Similar Threads
Thread Thread Starter Forum Replies Last Post
updating listbox content from a sub form maricar C# 14 August 12th, 2008 11:55 PM
How to Update a Listbox on Different Form boxwalah C# 2 February 24th, 2006 12:22 PM
submit form on listbox onchange webnitro Javascript How-To 3 December 10th, 2005 08:31 PM
Listbox selection in a form jpcoutts Access 1 November 10th, 2004 05:02 PM
form / listbox question nkrukovsky Access VBA 2 November 4th, 2003 09:16 AM

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.