0

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"))
        {

        }
Keven M
  • 972
  • 17
  • 47

1 Answers1

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

Steve
  • 213,761
  • 22
  • 232
  • 286
  • `.Select(k => k)` at the end of your linq is redundant :] – tom.maruska Dec 12 '13 at 21:14
  • 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"... – Keven M Dec 12 '13 at 22:18
  • 1
    Sorry, I haven't noticed the WPF tag. This applies to WinForms. [Here a q/a with the same problem solved for WPF](http://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type) – Steve Dec 12 '13 at 22:51