Akhilesh
Akhilesh

Reputation: 1313

How to access controls in windows form shown event?

I am trying to change the Visible state of controls from the form shown event.

I am reading the name of the controls from the database table and accessing it using this.Controls["controlname"].Visible. But some of the controls are not able to access from within this event. It is showing exception.

How can I access the controls from form shown event?

Upvotes: 0

Views: 393

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39132

Use Controls.Find() to search for it. As scheien pointed out, the control is probably inside a different container causing it not to be "found" with your original syntax. Here's a quick example:

    private void Form1_Shown(object sender, EventArgs e)
    {
        string ctlNameFromDatabase = "textBox1";

        Control[] matches = this.Controls.Find(ctlNameFromDatabase, true);
        if (matches.Length > 0)
        {
            // ... do something with "matches[0]" ...

            // you may need to CAST to a specific type:
            if (matches[0] is TextBox)
            {
                TextBox tb = matches[0] as TextBox;
                tb.Text = "Hello!";
            }
        }
        else
        {
            MessageBox.Show("Name: " + ctlNameFromDatabase, "Control Not Found!");
        }
    }

EDIT:

For MenuItems you'll have to flag the control name in the database as a "menu item" and then use this code, where menuStrip1 is the name of your MenuStrip, to find them:

        string menuName = "copyToolStripMenuItem";
        ToolStripItem[] matches = menuStrip1.Items.Find(menuName, true);
        if (matches.Length > 0)
        {
            matches[0].Visible = true;
        }

The same code will work for ToolStrips as well. For example, replace menuStrip1 with toolStrip1.

Upvotes: 2

Related Questions