?
Solved

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

Posted on 2007-11-26
20
Medium Priority
?
1,414 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 200 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
 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

 
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 700 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 1100 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

Stack Overflow Podcast - Developer Story

Welcome to the Stack Overflow podcast recorded Thursday July 20 at Stack Overflow Headquearters in NYC. Your hosts today are podcast regulars Jay Hanlon, David Fullerton, and Ilana Yitzhaki, plus the quite irregular Matt Sherman (Stack Overflow Engineering Manager extraordinaire)

Question has a verified solution.

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

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses

801 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