Solved

How to loop through .NET controls with the same name, just different numbers appended?

Posted on 2007-11-26
20
1,391 Views
Last Modified: 2013-12-16
I have 10 controls that have the same exact name, except for the number appendage.

Example:
      videoControl1
      videoControl2
      videoControl3
      videoControl4
      videoControl5
      videoControl6
      videoControl7
      videoControl8
      videoControl9
      videoControl10

So now I need to create a method that checks each one of these controls ".Text" property for a certain string.  Currently I can do this:
if (videoControl1.Text == string)
    doSomething();
else if (videoControl2.Text == string)
    doSomething();
else if (videoControl3.Text == string)
    doSomething();
else if (videoControl4.Text == string)
    doSomething();
else if (videoControl5.Text == string)
    doSomething();

etc...you get the idea.

What I'm curious to find out is ...if there is a way to do something in a FOR loop that appends the number to the "videoControl" text and then checks the
".Text" property?

For future readers coming here by Google/etc....The below code will not compile...it is just an example of what I'm looking for:
So something like:
for (int i = 0;i < 10; i++)
{
    if (videoControl + i.Text = string)
      DoSomething();
}

Any input is appreciated. Thanks.

- VT
0
Comment
Question by:VirtueTech
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 7
  • 3
  • +1
20 Comments
 
LVL 39

Assisted Solution

by:Pratima Pharande
Pratima Pharande earned 50 total points
ID: 20356075
string str ;
for (int i = 0;i < 10; i++)
{
   
    str = "videoControl" + i.Tostring();

    TextBox txt ;
    txt = (TextBox) Me.FindControl(str);
    if (txt.Text = =string)
      DoSomething();
}
0
 

Author Comment

by:VirtueTech
ID: 20356145
Hello Pratima,

Thnaks for the reply and knowledge. Question: In the code below...what is the "Me." part?

txt = (TextBox) Me.FindControl(str);

My code won't compile the "Me." part.
0
 

Author Comment

by:VirtueTech
ID: 20356159
Also...my application is a .NET C# Windows Form app....not a web application.

I'm not using the System.Web.UI namespace on the windows form. Should I add this namespace so that I can use the "FindControl" method?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Expert Comment

by:bdeschambault
ID: 20356167
He is referring to the container of the controls, a form for example.  You could also run a for each loop like below.  This may seem less efficient but it actually is more because the Me.FindControl method must search through all controls x times whereas mine runs through the controls only once.

int x = 0;

foreach(Control control in this.Controls)
{
   if(control.Name == ("videoControl" + x++))
      if(((TextBox)control).Text = "MyValue")
           DoSomething...

}
0
 
LVL 1

Expert Comment

by:bdeschambault
ID: 20356183
Here is the actual code that will compile

private void button1_Click(object sender, EventArgs e)
        {
            int x = 0;

            foreach (Control control in this.Controls)
            {
                if(control.Name == ("videoControl" + x++))
                    if(((TextBox)control).Text == "MyValue")
                        MessageBox.Show("Found My Value in control: " + control.Name);
            }
        }
0
 

Author Comment

by:VirtueTech
ID: 20356279
The control I'm using is from DevExpress.com:  'DevExpress.XtraLayout.LayoutControlItem'

ERROR:  Cannot convert type 'System.Windows.Forms.Control' to 'DevExpress.XtraLayout.LayoutControlItem'      

I'm getting this error on the code below in the snippet.

QUESTION:  Is there anything I can do, or do I need to contact DevExpress? Or is it just not possible to use this code on the 'DevExpress.XtraLayout.LayoutControlItem'?
public void upgradeLayoutbyCameraName(string camName)
{
	int x = 0;
 
	foreach (Control control in this.Controls)
	{
		if (control.Name == ("videoControl" + x++))
			if (((LayoutControlItem)control).Text == "MyValue")
				MessageBox.Show("Found My Value in control: " + control.Name);
	}
}

Open in new window

0
 
LVL 13

Expert Comment

by:SameerJagdale
ID: 20356314
Try this:

public void upgradeLayoutbyCameraName(string camName)
{
      foreach (DevExpress.XtraLayout.LayoutControlItem control in this.Controls)
      {
                 if (control.Text == "MyValue")
            MessageBox.Show("Found My Value in control: " + control.Name);
      }
}
0
 
LVL 1

Expert Comment

by:bdeschambault
ID: 20359366
The above code will crash if you have any controls in your form that are not type DevExpress.XtraLayout.LayoutControlItem.  First of all, for the library you are using, are you dropping the controls right onto the form or another container within the form?  Second, does the control you are using have a Name property?
0
 

Author Comment

by:VirtueTech
ID: 20360617
The above code did crash because it couldn't CAST the other controls on the form with the "DevExpress.XtraLayout.LayoutControlItem".

I'm dropping these controls onto the form. However, they are part of a BASE control. Here is the hierarchy:

DevExpress.XtraLayout.LayoutControl
------ DevExpress.XtraLayout.LayoutControlGroup
------------ DevExpress.XtraLayout.LayoutControlItem

Yes each one of these controls contains a NAME property.
0
 
LVL 1

Expert Comment

by:bdeschambault
ID: 20361153
This seems kind of odd because the collection this.Controls should only be able to store an instance of Control.  The funny thing is that it is finding your controls by name and is not crashing until the cast.  I would suspect that the object you are trying to cast is not really a LayoutControlItem.  Lucky for you, control has a .Text property.

public void upgradeLayoutbyCameraName(string camName)
{
      int x = 0;
 
      foreach (Control control in this.Controls)
      {
            if (control.Name == ("videoControl" + x++))
                  if (control.Text == "MyValue")
                        MessageBox.Show("Found My Value in control: " + control.Name);
      }
}
0
 

Author Comment

by:VirtueTech
ID: 20363109
bdeschambault:  The above code compiles and runs, but only allows me to check the ".Name" of the "DevExpress.XtraLayout.LayoutControl" control. I need to check the name of the LayoutControlItem control.

The hierarchy is below. How can I get to it?

DevExpress.XtraLayout.LayoutControl
------ DevExpress.XtraLayout.LayoutControlGroup
------------ DevExpress.XtraLayout.LayoutControlItem
0
 
LVL 13

Assisted Solution

by:SameerJagdale
SameerJagdale earned 175 total points
ID: 20363470
thanks bdeschambault: for letting me know that i have missed one important line of code.

VirtueTech:
try the attached code. I expect there could be multiple layoutcontrols, layoutgroups and layoutcontrolitems. correct me if i am wrong.

thanks
public void upgradeLayoutbyCameraName(string camName)
        {
            foreach (Control ctl in this.Controls)
            {
                if (ctl.GetType().Equals(typeof(DevExpress.XtraLayout.LayoutControl)))
                {
                    //no casting required .. as you know there is only layoutcontrolgroup controls in layoutcontrol.
                    foreach (DevExpress.XtraLayout.LayoutControlGroup layoutcontrolgroup in ctl.Controls)
                    {
                        //same applies here.
                        foreach (DevExpress.XtraLayout.LayoutControlItem control in layoutcontrolgroup.Controls)
                        {
                            if (control.Text == "MyValue")
                                MessageBox.Show("Found My Value in control: " + control.Name);
                        }
                    }
                }
            }
        }

Open in new window

0
 
LVL 1

Expert Comment

by:bdeschambault
ID: 20363476
Ok, I've done some research and know how the structure works now.  The LayoutControl was added to the form first and extends the control family.  You now need to get at the items within the LayoutControl.  However, for every layout control there is a LayoutControlGroup that can be accessed via the property Root.  Once you have the LayoutControlGroup you can then iterate through the items.  But be careful, if you've added more LayoutControlGroups onto your LayoutControl then you will have to recursively go through them!  Now, are you naming the LayoutControlItem "VideoControl"+x or the control contained within the LayoutControlItem?  Both will have a name and text property.  Experiment with the code below.

foreach (LayoutControlItem item in layoutControl.Root.Items)
{
   if(item.Name == "videoControl" + x)
     if(item.Text == "MyValue")
       Do Something
}

or

foreach (LayoutControlItem item in layoutControl.Root.Items)
{
   if(item.Control.Name == "videoControl" + x)
     if(item.Control.Text == "MyValue")
       Do Something
}

Hope this solves it for ya
0
 
LVL 1

Expert Comment

by:bdeschambault
ID: 20363502

Sameer Jagdale:  There is no Controls property within a LayoutControlGroup, you need to use the Items property.  Also, recursion is needed because of the fact that LayoutControl.Root.Items can contain both LayoutControlItems and LayoutControlGroups.  

VirtueTech:  My above code will not work if you have gone too deep with groups!  It only supports one group deep containing only LayoutControlItems.  Anything else will require a recursive solution.  This architecture seems to be alot of overhead.  What does it provide that System.Windows.Forms does not besides headaches?
0
 
LVL 13

Expert Comment

by:SameerJagdale
ID: 20363530
bdeschambault: thanks for the info. I haven't worked with devexpress, so am not aware of the fact that there is no controls property. however, i thought since it is a control it must inherit from control class.
0
 
LVL 1

Accepted Solution

by:
bdeschambault earned 275 total points
ID: 20363551
Sameer:  Me niether, here is the article I referenced if you are interested in learning more.  However, the framework seems to be a bit convoluted!

http://www.devexpress.com/Help/?document=xtralayoutcontrol/DevExpressXtraLayout.htm&levelup=true
0
 

Author Comment

by:VirtueTech
ID: 20363683
Wow ...thanks for working so hard on this for me. I'm giving it a shot now.

Question: You mentioned this seem like alot of overhead to go through. Am I better off just adding simple IF/ELSE statements for each control I want to change its "Visibility" property on?

PS: I've only got one LayoutControlGroup. For now.
0
 

Author Comment

by:VirtueTech
ID: 20363812
What about creating a control array?  Can I use a control array on controls that are already added to the form?
0
 

Author Closing Comment

by:VirtueTech
ID: 31411145
Hello everyone,

For users coming to this thread from Google, or any other search engine, the experts in this thread didn't actually solve my problem, but helped tremendously. The solution was found within the DevExpress layout API. Here is the code I used:

public void upgradeLayoutbyCameraName(string camName)
{
      string str ;
      for (int i = 1;i < 17; i++)
      {
            BaseLayoutItem baseVidControl = new LayoutControlItem();
            str = "videoControl" + i.ToString();
            if (this.layoutControl1.Items.FindByName(str) != null)
            {
                  baseVidControl = this.layoutControl1.Items.FindByName(str);
                  if (baseVidControl.Text == camName)

                        baseVidControl.Visibility = LayoutVisibilityConvertor.FromBoolean(true);
                  else
                        baseVidControl.Visibility = LayoutVisibilityConvertor.FromBoolean(false);
            }                        
      }
      InZoomMode = true;
}

As for the point split. I gave it based on the amount of work I thought each expert helped. Thanks everyone.
0
 

Author Comment

by:VirtueTech
ID: 20367227
My ending comment didn't seem to be added to the thread...so I'm adding it here:

===========================================================

Hello everyone,

For users coming to this thread from Google, or any other search engine, the experts in this thread didn't actually solve my problem, but helped tremendously. The solution was found within the DevExpress layout API. Here is the code I used:

public void upgradeLayoutbyCameraName(string camName)
{
      string str ;
      for (int i = 1;i < 17; i++)
      {
            BaseLayoutItem baseVidControl = new LayoutControlItem();
            str = "videoControl" + i.ToString();
            if (this.layoutControl1.Items.FindByName(str) != null)
            {
                  baseVidControl = this.layoutControl1.Items.FindByName(str);
                  if (baseVidControl.Text == camName)

                        baseVidControl.Visibility = LayoutVisibilityConvertor.FromBoolean(true);
                  else
                        baseVidControl.Visibility = LayoutVisibilityConvertor.FromBoolean(false);
            }                        
      }
      InZoomMode = true;
}

As for the point split. I gave it based on the amount of work I thought each expert helped. Thanks everyone.
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question