c# - Foreach loop through controls that are textbox doesn't return -
i've used code before in program, i'm having trouble understanding why won't run code after second line.
foreach (control c in controls) if (c.gettype() == typeof(textbox)) //doesn't run further { if ((string)c.tag == "filled") { ... } ... } i'm either missing minor little detail or else incorrect. ideas?
edit: textboxes inside panel.
when call control.controls, return controls @ outermost level. won't recursively descend container controls hold other controls.
if controls in container, need use container's .controls property instead.
alternatively can generalize writing method recursively return controls parent , it's children, so:
public ienumerable<control> allcontrols(control container) { foreach (control control in container.controls) { yield return control; foreach (var innercontrol in allcontrols(control)) yield return innercontrol; } } you can use instead of control.controls follows:
private void test() // assuming member of form other class derived control { var textboxeswithfilledtag = allcontrols(this).oftype<textbox>() .where(tb => (string) tb.tag == "filled"); foreach (var textbox in textboxeswithfilledtag) debug.writeline(textbox.text); } as comment says, i'm assuming test() method member of form or class derived control. if isn't, have pass parent control it:
private void test(control container) { var textboxeswithfilledtag = allcontrols(container).oftype<textbox>() .where(tb => (string) tb.tag == "filled"); foreach (var textbox in textboxeswithfilledtag) debug.writeline(textbox.text); } the following method has identical results 1 above, reference (and more readable imho):
private void test(control container) { foreach (var textbox in allcontrols(container).oftype<textbox>()) if ((string)textbox.tag == "filled") debug.writeline(textbox.text); } for code, button click handler might this:
void button1_click(object sender, eventargs e) { foreach (var c in allcontrols(this).oftype<textbox>()) { if ((string) c.tag == "filled") { // here put code textbox 'c' } } } note need allcontrols() method, of course.
Comments
Post a Comment