• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 357
  • Last Modified:

Need to iterate through all the control on a grid on a tab item

Hi experts,

I need to go through the entire collection of elements/controls on the grid.. I am using the following piece of code

public void clear_all(Grid g)
        {
            UIElementCollection cc = g.Children;
foreach (Control ctrl in cc)
            {
                if (ctrl.GetType() == typeof(TextBox))....etc

However during runtime the statement "foreach (Control ctrl in cc)" throws an error for the image control. The error message reads "Unable to cast object type system.windows.controls.image into system.windows.controls.control".....

This is urgent and I need to fix this right away! all help is greatly appreciated.. Thanks!
0
Pavithra_S
Asked:
Pavithra_S
  • 2
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
use
foreach (FrameworkElement ctrl in cc)
            {

rather than
foreach (Control ctrl in cc)
0
 
Meir RivkinFull stack Software EngineerCommented:
or use UIElement, whatever suit your needs.
0
 
Ramone_HamiltonCommented:
A quick fix:  Just use try - continue
public void clear_all(Grid g)
        {
            UIElementCollection cc = g.Children;
try
{
foreach (Control ctrl in cc)
            {
                if (ctrl.GetType() == typeof(TextBox))....
}
catch
{
 continue;
}

Open in new window

0
 
Pavithra_SAuthor Commented:
Thanks a lot!! Worked awesome... I was wondering why it failed to see the image control as a control...
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now