-1

I am trying to change Label text In parent Form from Child form but I am getting this error Object reference not set to an instance of an object. where is the mistake ? Here is code I am Using

private void btnMedicalClgList_Click(object sender, EventArgs e)
        {
            this.ParentForm.Controls["lblMenuItem"].Text = "Medical College List";//getting error here
            ShowMedicalClgList medifrm = new ShowMedicalClgList();
            medifrm.MdiParent = this.ParentForm;
            this.Hide();
            medifrm.Show();           
        }
VahidNaderi
  • 2,448
  • 1
  • 23
  • 35
Durga
  • 1,283
  • 9
  • 28
  • 54
  • 2
    `this.ParentForm.Controls["lblMenuItem"]` is probably where your null reference exception is coming from. – JeremiahDotNet Sep 05 '13 at 15:04
  • 3
    @JeremiahDotNet Well it certainly isn't coming from the string literal – DGibbs Sep 05 '13 at 15:05
  • 2
    Maybe `this.ParentForm` is null or there is no control name `lblMenuItem`. Try debugging. – Alessandro D'Andria Sep 05 '13 at 15:05
  • @Durga You'll need to step through your code and check that `lblMenuItem` is found in `ParentForm.Controls` – DGibbs Sep 05 '13 at 15:06
  • possible duplicate of [What is a NullReferenceException in .NET and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net-and-how-do-i-fix-it) – User Sep 05 '13 at 15:07
  • You can't access controls in Controls array by providing the control's name as the indexer. – VahidNaderi Sep 05 '13 at 15:08
  • label is there but while debugging it is showing me null,why is it so? @VahidND than what is the right way can you please shoe me – Durga Sep 05 '13 at 15:11

1 Answers1

1

As I said in my comment you can't use a control's name as the indexer of Controls collection to get it but you can iterate through the controls collection find the desired control and do whatever you want with it, try this:

Label lbl = null;
foreach (var control in this.ParentForm.Controls)
{
    if (((Control)control).Name == "lblMenuItem")
    {
        lbl = (Label)control;
        break;
    }
}
if (lbl != null)
    lbl.Text = "Medical College List";

or if you want to write less code :

Control[] foundControls = this.Controls.Find("lblMenuItem", true);
if (foundControls.Any())
    foundControls.First().Text = "Medical College List";
VahidNaderi
  • 2,448
  • 1
  • 23
  • 35
  • Yes this works as you said ,changing `this.Controls.Find` to `this.ParentForm.Controls.Find` in your second Part of code, both works – Durga Sep 05 '13 at 15:57
  • for first element you used this `foundControls.First().Text` what to use for second element? – Durga Sep 05 '13 at 16:08
  • We're searching for a control named "lblMenuItem" you cannot have more than one control on your form with this name, so you'll get one if any not more. – VahidNaderi Sep 05 '13 at 16:16