1

Is there a way in C# to reference a control, in my case a TextBox, by using the value of a string variable? I am using the code below to make a single method that multiple control can use for the 'LostFocus' event. The sender TextBox then needs to calculate results based on the contents of other TextBoxes. The problem is that there are about 12 rows of TextBoxes, and while this code works to reuse the event method, I can't think of a way to reference the correct boxes that are not the sender. All of the boxes have similar names (ex - miCellSaturation, miCellRecords, orSaturation, orRecords), so my thinking was that if I can isolate part of the TextBox name with a Substring command, and then concatenate that with another string to form the complete TextBox name, this would work. I can do all that, but I don't know of a way to use the concatenated string to reference that box. Would this require iterating through all the boxes until it matches the correct name?

        TextBox box = (TextBox)sender;
        string boxName = box.Name;

        if(boxName.EndsWith("Saturation"))
        {

        }

1 Answer 1

2

Not sure to understand you problem correctly, but if you need to find the references to a particular type of control with its name ending with a predefined string, then you could use

var list = YourForm.Controls.OfType<TextBox>()
                   .Where(x => x.Name.EndsWith("YourString"));

foreach(TextBox t in list)
{
   Console.WriteLine(t.Name);
   ......
}

This could work only if your searched controls are directly included in the controls collection of the form. If these textboxes are included in some control container then you need to apply these lines to the appropriate control container instead of the form

Sign up to request clarification or add additional context in comments.

3 Comments

.Select(k => k) at the end of your linq is redundant :]
Does this apply for WPF, or is this for Windows Forms? I ask because the ".Controls" does not pop up in Intellisense, and you used the name "YourForm"...
Sorry, I haven't noticed the WPF tag. This applies to WinForms. Here a q/a with the same problem solved for WPF

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.