Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Locating a control with a string

Status
Not open for further replies.

pjmartins

Programmer
Nov 5, 2004
4
US
I have created several textboxes and I'm trying to write code for reading and writing to each textbox, but coding each box individually would take forever, is there a way to locate each textbox when the name of the textbox is stored in a string and then to reference it with a temporary textbox? I saw something like this TempTextBox = FindControl("TextBox1") as TextBox; but I can't find a way to use FindControl.
 
here is one i wrote, on a click event behind 14 of the boxes on a form i simply wanted to highlight all the text if a user clicked in any of these
Code:
private void HighlightAllInTimeBox(object sender)
        {
            TextBox aTextbox;
            string temp;
            
            aTextbox = (TextBox)sender;
            
            if (aTextbox.Name.ToString() == "txtMSTime" || aTextbox.Name.ToString() == "txtMFTime" 
                || aTextbox.Name.ToString() == "txtTSTime" || aTextbox.Name.ToString() == "txtTFTime" 
                || aTextbox.Name.ToString() == "txtWSTime" || aTextbox.Name.ToString() == "txtWFTime"
                || aTextbox.Name.ToString() == "txtTSTime" || aTextbox.Name.ToString() == "txtTFTime"
                || aTextbox.Name.ToString() == "txtFSTime" || aTextbox.Name.ToString() == "txtFFTime"
                || aTextbox.Name.ToString() == "txtSSTime" || aTextbox.Name.ToString() == "txtSFTime"
                || aTextbox.Name.ToString() == "txtSSTime" || aTextbox.Name.ToString() == "txtSFTime")
            {
                temp = aTextbox.Text.Trim();
                if(temp.Length > 0)
                {
                    aTextbox.Select(0, temp.Length);
                }
            }
        }
[code]

by the way, it would have worked without the long if but to make sure other people didnt call it i put it in. hope this helps

Age is a consequence of experience
 
that's a big if statement.

I would add all of your controls to a HashTable and reference the textboxes by name.

for example:

HashTable tbhash = new HashTable;

foreach (Textbox t in pnlContent.Controls)
{
//Loop through each textbox in a panel called pnlContent

tbhash.Add(t.Name, t);
//Add the textbox to the hash table using its name as the key
}

Then later on you would simply call

public void DoSomething()
{
TextBox tb = (TextBox)tbhash["textBox1"];

//and magically you have your textbox to work with
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top