473,763 Members | 1,333 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

InvalidCastExce ption when getting Text from a Label referenced by dynamic string

3 New Member
.NET Version: 3.5
Ok, I recieve an error (System.Invalid CastException was unhandled. Message="Unable to cast object of type 'System.Windows .Forms.Control[]' to type 'System.Windows .Forms.Label'." ) when trying to get Text from a Label referenced by a dynamicly built string.

Here's my situation; I have an array of 250 labels named l1 - l250. What I want to do is loop through them using this while statement:
Expand|Select|Wrap|Line Numbers
  1. int c = 1;
  2. while (c < 251)
  3. {
  4. string k = "l" + c.ToString(); //dynamic name of Control(Label)
  5. object ka = Controls.Find(k, true); 
  6. string ct = ((Label)ka).Text;  //<<Error Occurs Here
  7. build = build + ct;
  8. c++;
  9. }
and get the text value of each to build a string named build.

I don't get any build errors, just this while debuging.

While debuging I can go down to view my local variables. When looking through these, I can view the contents of object ka; it does contain the correct Text value of the correct Label I want to "access". I just don't understand how to get there. The text value is listed under "[0]" which is the only subcatagory for "ka".
Jun 11 '10 #1
3 2083
ThatThatGuy
449 Recognized Expert Contributor
@Promedeus
If it would have been Object to Label then its acceptable...
But an Object[] to a single Label is unacceptable...

Your Control.Find() method is getting moer then one label...

so you can loop in a collection like this
Expand|Select|Wrap|Line Numbers
  1. foreach(object o in Controls.Find(k, true))
  2. {
  3. st+=((Label)o).Text;
  4. }
  5.  
Jun 11 '10 #2
GaryTexmo
1,501 Recognized Expert Top Contributor
I believe you can also get the object directly by name. Additionally, you can cast it directly when you retrieve it and then perform a null check on it, as such.

Expand|Select|Wrap|Line Numbers
  1. Label theLabel = this.Controls["myLabelName"] as Label;
  2. if (theLabel != null)
  3. {
  4.   ...
  5. }
The "as" operator will attempt to cast the object to the desired type. If it can't, it will return null, otherwise it will return the properly cast object.

With the code you've got now, it's entirely possible that you may have an object named say, "l12" that happens to be a TextBox due to being misnamed. Therefore your current code would throw an exception.

Hope that helps!
Jun 11 '10 #3
ThatThatGuy
449 Recognized Expert Contributor
@Promedeus
Or Better you can give the labels a common Tag...

Under the Tag property of the Label...
And then retrieve all labels with the tag name..

That's a better option... by probably a LINQ query
Jun 14 '10 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

2
2154
by: FrodoBaggins | last post by:
Dear Team, I am trying to use stylesheets on a web form. Initially, I created a folder named 'styles' within the WebUI project. In this I created the following stylesheet named 'drivingschool.css': body {
17
14362
by: Olivier Bellemare | last post by:
I've tried to make a function that returns the middle of a string. For example: strmid("this is a text",6,4); would return "is a". Here is my code: char *strmid(char *texte, int depart, int longueur) { char *resultat = " "; char *temporaire = " "; int nbr;
11
1787
by: jcrouse | last post by:
I’m using VB .Net 2003. I am reading a file into memory. Here is a sniplet of the file ” section. I have the code returning what character the string “” starts at but don’t know the command or syntax to start at a certain character number (which I have) and then read until the first blank line then put it into another variable After that I want to do the same thing, kind of, and put the parts after the “=” sign into separate...
24
2404
by: Sillaba atona | last post by:
I use this code to read dynamic string: char *s1; ....... puts("Inserire una stringa: "); while((*s1++=getchar())!='\n'); *s1='\0'; The compilation (ANSI C) is OK but I receive an error during the execution.
5
59596
by: Yohan Blurp | last post by:
Hi, Here is sample page to show you the problem : <html><body> <form action="/cgi-bin/test.cgi" method="post"> Data Path : <input type="text" size="50" value="C:\Test Data\May 2007.xls" style='border: thin solid #FFFFFF'></form> </body></html>
3
6306
by: bhanubalaji | last post by:
hi, I am unable to disable the text(label) in javascript..it's working fine with IE,but i am using MOZILLA.. can any one help regarding this.. What's the wrong with my code? I am sending my code here.. Thanks in Advance... Regards
2
2370
damonreid
by: damonreid | last post by:
Is it possible to pass a field to a text label when a form loads? I have tried Private Sub Form_Load() Dim textName As String textName = "Text Edit Text" Me.Text29 = textName
6
4975
by: dgleeson3 | last post by:
Hello All I have VB code (.Net 2005) reading from an SQL server 2005 database. Im getting InvalidCastException when doing reader.GetInt32(0) Im simply reading an int from a simple database. It has two columns, User and Tel number. User is filled with 1,2,3 and tel number has 3 telephone numbers. The User data column is specified as (PK, int, not null) in MS SQL
1
1697
by: kenneth6 | last post by:
Windows form app: 1. how to get text label updated? 2. how to get text label assigned with a variable value (integer / string)?
4
4889
by: Michael Munch | last post by:
Hi I want to read the value of af text-field, create dynamic, in a form. Se below a small test-site to do that (but readning fails): I use the function Test_Read for reading the value from the dynamic create text-field "txtName". I thanks...
0
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9998
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9938
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9822
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3523
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.