Sherif Sanad
Sherif Sanad

Reputation: 45

How can I chang the text of all controls on form from another form

I have two form (Form1,form2) this code on form2 ... I make a loop of all controls on form1 and get name of the control (ControlName) I want send any text (ex."sherif") to this control (case button)

 foreach (Control ctrl in form1.Controls)
{
    form1.Controls[ControlName]).Text = "sherif";
}

error message appears NullReferenceException Object reference not set to an instance of an object. if the pointer stop above [ControlName] read name of control, but when continue Comes an Null value

Upvotes: 1

Views: 247

Answers (4)

Developer
Developer

Reputation: 8636

Try this

foreach (Control c in form1.Controls)
{

    if (c!= null)
    {
        c.text="Sherif";
    }
}

Upvotes: -1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236248

This method recursively returns all controls of form:

public IEnumerable<Control> GetChildControls(Control parent)
{
    foreach(Control ctrl in parent.Controls)
    {
        yield return ctrl;

        if (ctrl.HasChildren)
            yield return GetChildControls(ctrl);
    }
}

Updating text:

foreach(var ctrl in GetChildControls(form1))
    ctrl.Text = "sherif";

Upvotes: 1

algreat
algreat

Reputation: 9002

You have to loop all controls. Some of them can be inside panels. Use this recursive method:

private void SetText(Control control, string text)       
{
     foreach (Control ctrl in control.Controls)
     {
         ctrl.Text = text;
         SetText(ctrl, text);
     }
}

Usage:

SetText(form1,  "sherif");

Upvotes: 0

Blachshma
Blachshma

Reputation: 17395

If you just want to change the Text properties of all controls in a form, this should do it:

foreach (Control ctrl in form1.Controls)
{
   ctrl.Text = "sherif";
}

Note this will only change the controls in the top level and not nested controls....

If you need this for nested controls too, do it recursively:

 public void RecursiveChange(Control control)       
 {

    foreach (Control ctrl in control.Controls)
    {
       RecursiveChange(ctrl);
       ctrl.Text = "sherif";
    }
 }

Upvotes: 2

Related Questions