Ben
Ben

Reputation: 759

How to get a control by name

I'm struggling to get the right context with how to get a TextBox currently in my form.

Right now I have a button that when pressed will allow the user to choose a folder. I'd like to take that path and put it in a TextBox which is currently named installPath.

namespace CustomLauncher
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void browse_Click(object sender, EventArgs e)
        {
            //browse to select a folder
            FolderBrowserDialog folder = new FolderBrowserDialog();
            DialogResult result = folder.ShowDialog();
            if (result == DialogResult.OK)
            {
                MessageBox.Show("You chose" + folder.SelectedPath);
            }
            else if (result == DialogResult.Cancel)
            {
                return;
            }
        }

I've seen various attempts like...

this.Controls.Find("installPath"); //visual studio didn't like this

Control myControl1 = FindControl("installPath"); //didn't like this either

I've also seen a few other ways of doing this. Though I can't seem to find one that visual studio will accept. I feel like I'm missing something rather obvious/huge about the context of this event listener which is why I'm not able to figure out how to accomplish this.

Upvotes: 0

Views: 156

Answers (2)

Habibillah
Habibillah

Reputation: 28705

Try to use this code:

private void browse_Click(object sender, EventArgs e)
{
    //browse to select a folder
    FolderBrowserDialog folder = new FolderBrowserDialog();
    DialogResult result = folder.ShowDialog();
    if (result == DialogResult.OK)
    {
        installPath.Text = folder.SelectedPath;
        MessageBox.Show("You chose" + folder.SelectedPath);
    }
    else if (result == DialogResult.Cancel)
    {
        return;
    }
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460268

Why not this.installPath.Text = folder.SelectedPath? Is the TextBox on another form?

Btw, you've seen the FindControl approaches on ASP.NET sites.

If you're using .NET 2 or greater you can use the Control.ControlCollection.Find Method.

TextBox txtInstallPath = (TextBox)this.Controls.Find("installPath", true)[0];

Upvotes: 2

Related Questions