473,394 Members | 2,071 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

NullReference question

Moe haroon
Hi All, I'm very new to c#, programming in general :-)

I'm trying to do a simple test and its failing, hopfully you guru's can answer it in a jiffy...

Setup:
- Form1 with toolstrip and toolstriplabel with value "TEST"
- Form2 with a Button

Test: Button press will change the label value on Form1 toolstriplabel to "PASSED";

Here is the code... [not working]

Expand|Select|Wrap|Line Numbers
  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form1 : Form
  4.     {
  5.         public Form1()
  6.         {
  7.             InitializeComponent();
  8.  
  9.         }
  10.  
  11.         private void Form1_Shown(object sender, EventArgs e)
  12.         {
  13.             Form2 ChildForm = new Form2();
  14.             ChildForm.ShowDialog();
  15.         }
  16.     }
  17. }
  18.  
  19.  
Here is Form2

Expand|Select|Wrap|Line Numbers
  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form2 : Form
  4.     {
  5.         public Form2()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.  
  10.         private void button1_Click(object sender, EventArgs e)
  11.         {
  12.             try
  13.             {
  14.                 Form1 MainForm = new Form1();
  15.                 MainForm.Controls["toolStripStatusLabel1"].Text = "Passed";
  16.  
  17.             }
  18.             catch (NullReferenceException nre)
  19.             {
  20.                 MessageBox.Show("Error:\n" + nre.Message);
  21.             }
  22.         }
  23.     }
  24. }
  25.  
I'm getting NullReferenceException... What do I need to instantiate?
Oct 12 '10 #1

✓ answered by Moe haroon

Thanks Aimee, that did the trick. As stated in my post I'm a beginer and would like to follow best practices. Would you concur with Curtis earlier reply to this post that I should be using the public property rather than going the route of having child forms manipulate objects in parent form.

On that note I've made some modification, still trying to figure out how the whole property value set option works, please see the code below and advise how to go about utilizing the set value

thanks

Expand|Select|Wrap|Line Numbers
  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form1 : Form
  4.     {
  5.  
  6.         Form2 ChildForm;
  7.  
  8.         public Form1()
  9.         {
  10.             InitializeComponent();
  11.         }
  12.  
  13.         public class GetTSLabel
  14.         {
  15.             private string LabelValue = string.Empty;
  16.             public string Value
  17.             {
  18.                 get { return LabelValue; }
  19.                 set { LabelValue = value; }
  20.             }
  21.  
  22.         }
  23.  
  24.         /* RESOLVED BASED ON AIMEE's POST
  25.         private void Form1_Shown(object sender, EventArgs e)
  26.         {
  27.             ChildForm = new Form2();
  28.             ChildForm.ShowDialog(this);
  29.         }
  30.          */
  31.  
  32.         private void Form1_Shown(object sender, EventArgs e)
  33.         {
  34.             ChildForm = new Form2();
  35.             ChildForm.ShowDialog();
  36.         }
  37.  
  38.  
  39.     }
  40. }
  41.  
Form2:
Expand|Select|Wrap|Line Numbers
  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form2 : Form
  4.     {
  5.  
  6.         public Form2()
  7.         {
  8.             InitializeComponent();
  9.  
  10.         }
  11.  
  12.         private void button1_Click(object sender, EventArgs e)
  13.         {
  14.             try
  15.             {
  16.                 Form1.GetTSLabel TSLabel = new Form1.GetTSLabel();
  17.                 TSLabel.Value = "Passed";
  18.                 MessageBox.Show("Name: " + TSLabel.Value);
  19.  
  20.                 /* RESOLVED BASED ON AIMEE's POST
  21.                   Form1 form1 = (Form1)this.Owner;
  22.                 form1.toolStripStatusLabel1.Text = "Passed";
  23.                  */ 
  24.             }
  25.             catch (NullReferenceException nre)
  26.             {
  27.                 MessageBox.Show("Error:\n" + nre.Message);
  28.             }
  29.         }
  30.     }
  31. }
  32.  
When i run the following I can see the TSLabel.Value is set to "PASSED". I guess what I'm asking is how do I go about setting the toolstriplabel.text to TSLabel.Value{set in Form2} in Form1

thanks Moe

7 1635
Curtis Rutland
3,256 Expert 2GB
You're creating a new instance of Form1, not getting the one that already exists. If you plan on doing anything with Form1 in Form2, you'll need a reference to it.

You could modify Form2's:
Expand|Select|Wrap|Line Numbers
  1. private Form1 form1;
  2.  
  3. public Form2(Form1 form1)
  4. {
  5.   InitializeComponent();
  6.   this.form1 = form1;
  7. }
And you'd have to create it like this:
Expand|Select|Wrap|Line Numbers
  1. Form2 childForm = new Form2(this);
  2. childForm.ShowDialog();
But it's bad practice to directly manipulate a parent's controls from a child form.

What you should do is make a public property on Form1 that gets the value you're looking for, and use that.
Oct 12 '10 #2
thanks Curtis for a quick reply... I'm still getting the same error... not sure If I got all the instructions you posted placed correctly.... Here is the code

Form1:
Expand|Select|Wrap|Line Numbers
  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form1 : Form
  4.     {
  5.         public Form1()
  6.         {
  7.             InitializeComponent();
  8.  
  9.         }
  10.  
  11.         private void Form1_Shown(object sender, EventArgs e)
  12.         {
  13.             Form2 ChildForm = new Form2(this);
  14.             ChildForm.ShowDialog();
  15.         }
  16.     }
  17. }
  18.  
Form2:
Expand|Select|Wrap|Line Numbers
  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form2 : Form
  4.     {
  5.         private Form1 form1;
  6.  
  7.         public Form2(Form1 form1)
  8.         {
  9.             InitializeComponent();
  10.             this.form1 = form1;
  11.         }
  12.  
  13.         private void button1_Click(object sender, EventArgs e)
  14.         {
  15.             try
  16.             {
  17.                form1.Controls["toolStripStatusLabel1"].Text = "Passed";
  18.  
  19.             }
  20.             catch (NullReferenceException nre)
  21.             {
  22.                 MessageBox.Show("Error:\n" + nre.Message);
  23.             }
  24.         }
  25.     }
  26. }
  27.  
After the change I am still getting the same error
Oct 13 '10 #3
Aimee Bailey
197 Expert 100+
When using dialogues, you should use the Owner mechanism...

Expand|Select|Wrap|Line Numbers
  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form1 : Form
  4.     {
  5.         Form2 otherForm;
  6.  
  7.         public Form1()
  8.         {
  9.             InitializeComponent();
  10.         }
  11.  
  12.         private void Form1_Shown(object sender,
  13.                                  EventArgs e)
  14.         {
  15.             otherForm = new Form2();
  16.             otherForm.ShowDialog(this);
  17.         }
  18.  
  19.     }
  20. }
  21.  
Expand|Select|Wrap|Line Numbers
  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form2 : Form
  4.     {
  5.         public Form2()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.  
  10.         private void button1_Click(object sender,
  11.                                    EventArgs e)
  12.         {
  13.             Form1 form1 = (Form1)this.Owner;
  14.             form1.toolStripStatusLabel1.Text = "Passed";
  15.         }
  16.     }
  17. }
  18.  
this ensures that the parent is passed correctly.

Aimee.
Oct 13 '10 #4
Thanks Aimee, that did the trick. As stated in my post I'm a beginer and would like to follow best practices. Would you concur with Curtis earlier reply to this post that I should be using the public property rather than going the route of having child forms manipulate objects in parent form.

On that note I've made some modification, still trying to figure out how the whole property value set option works, please see the code below and advise how to go about utilizing the set value

thanks

Expand|Select|Wrap|Line Numbers
  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form1 : Form
  4.     {
  5.  
  6.         Form2 ChildForm;
  7.  
  8.         public Form1()
  9.         {
  10.             InitializeComponent();
  11.         }
  12.  
  13.         public class GetTSLabel
  14.         {
  15.             private string LabelValue = string.Empty;
  16.             public string Value
  17.             {
  18.                 get { return LabelValue; }
  19.                 set { LabelValue = value; }
  20.             }
  21.  
  22.         }
  23.  
  24.         /* RESOLVED BASED ON AIMEE's POST
  25.         private void Form1_Shown(object sender, EventArgs e)
  26.         {
  27.             ChildForm = new Form2();
  28.             ChildForm.ShowDialog(this);
  29.         }
  30.          */
  31.  
  32.         private void Form1_Shown(object sender, EventArgs e)
  33.         {
  34.             ChildForm = new Form2();
  35.             ChildForm.ShowDialog();
  36.         }
  37.  
  38.  
  39.     }
  40. }
  41.  
Form2:
Expand|Select|Wrap|Line Numbers
  1. namespace WindowsFormsApplication1
  2. {
  3.     public partial class Form2 : Form
  4.     {
  5.  
  6.         public Form2()
  7.         {
  8.             InitializeComponent();
  9.  
  10.         }
  11.  
  12.         private void button1_Click(object sender, EventArgs e)
  13.         {
  14.             try
  15.             {
  16.                 Form1.GetTSLabel TSLabel = new Form1.GetTSLabel();
  17.                 TSLabel.Value = "Passed";
  18.                 MessageBox.Show("Name: " + TSLabel.Value);
  19.  
  20.                 /* RESOLVED BASED ON AIMEE's POST
  21.                   Form1 form1 = (Form1)this.Owner;
  22.                 form1.toolStripStatusLabel1.Text = "Passed";
  23.                  */ 
  24.             }
  25.             catch (NullReferenceException nre)
  26.             {
  27.                 MessageBox.Show("Error:\n" + nre.Message);
  28.             }
  29.         }
  30.     }
  31. }
  32.  
When i run the following I can see the TSLabel.Value is set to "PASSED". I guess what I'm asking is how do I go about setting the toolstriplabel.text to TSLabel.Value{set in Form2} in Form1

thanks Moe
Oct 13 '10 #5
Aimee Bailey
197 Expert 100+
I think it's ok to modify parent controls as they each implement their own properties anyway. Properties at the end of the day are there to help access/transport, so unless you require a level of direction control, I don't see the point in restricting access to the controls on the parent.
Oct 13 '10 #6
Curtis Rutland
3,256 Expert 2GB
I think it's ok to modify parent controls as they each implement their own properties anyway.
I'm sorry, but that's just bad practice. Forms should be as self-contained as possible. You shouldn't be directly modifying a form's UI elements from another form. If you were to delete or rename a TextBox, for example, then now you have to trace down everywhere else you used that TextBox.

If you use a Property, though, all you have to do is change the get and set methods, and it's updated everywhere.

That's the whole point of properties. That's also the reason why fields shouldn't be public. It's called "encapsulation" and it's a well known and accepted Object Oriented design pattern.
Oct 13 '10 #7
Aimee Bailey
197 Expert 100+
I am a loyal follower of the OOP practices, allthough im self minded enough to know that sometimes it is capable of having it's own impracticalities, You are right, properties make more sense on this topic. But the user posting the question requested a solution to a non strict OOP problem, rather than a brief history on encapsulation.

When it comes to WinForms or indeed WPF, I believe that actually it is bad practice to use a model that allows for non-persistant interfaces, no matter how pretty, disrupting the interface can confuse the user. This is where HCI comes into the picture and we start to ask "why would you delete or rename a TextBox in the first place?".

Alot of people brush past HCI now days without any clue as to why it's there in the first place, heck im sure there are a vast many people with VS open right now with absolutely no understanding of the subject, I deeply encourage everyone to take a look at what it is, because OOP is not the be all and end all.

Aimee.
Oct 14 '10 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Taras | last post by:
This code has been working for some months - suddenly it get a NullReference error Private Sub btnShowProj_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowProj.Click...
2
by: Larry Re | last post by:
I've written a small C# app which appears to work perfectly except for the fact that I get a NullReference exception when I close the form using the red 'X' in the upper right hand corner of the...
3
by: Tom | last post by:
Hi, I built a class project (classproject.dll) and a web project (webproject.dll). The web project needs to reference to that class project. They can compile without error. But, it has...
3
by: astro | last post by:
I want to build a Filter form that displays a list of values in a listbox which the user selects from. The values in this listbox are passed to the filterform. When the user closes this filter...
5
by: Paul Cheetham | last post by:
Hi, I have moved a fairly large project from VS2003 to VS2005, and now trying to get it running. It now compiles OK after minimal changes, but I am now getting a NullReference Exception on...
0
by: studio60podcast | last post by:
I'm defining the ItemUpdating event for a DetailsView control, but when I try to access the e.NewValues collection, it's throwing a NULLReference exception. Any thoughts? <asp:DetailsView...
1
by: Rama Jayapal | last post by:
i have written the following code to call a method in a class like in the aspx.cs page List<string> surls = new List<string>(); Cweb.GetMainUrls(document,ref surls); Response.Write(surls); ...
4
by: yogarajan | last post by:
hi i had developed pop3 Account mail view in my web page but i got error in (System.NullReference Exception: Object reference not set) NetStrm.Write(szData, 0, szData.Length); - this line ...
0
by: =?Utf-8?B?RGlzcEV2ZW50QWR2aXNlIGZhaWxzIHdpdGggMHg4 | last post by:
Hi, I have a beginner's question and I'm not even sure whether it's an asp question, an Exchange server question or an x64 question... I've been experimenting with HttpModules. I want to use one in...
6
by: Steve | last post by:
Hi All I have a windows forms Application (SAM) in vb.net 2008 using .net framework V2 One and only one customer out of 30 customers is getting errors daily where they have to close and...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.