By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,837 Members | 1,842 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,837 IT Pros & Developers. It's quick & easy.

InvalidCastException when getting Text from a Label referenced by dynamic string

P: 3
.NET Version: 3.5
Ok, I recieve an error (System.InvalidCastException 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
Share this Question
Share on Google+
3 Replies

Expert 100+
P: 449
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. }
Jun 11 '10 #2

Expert 100+
P: 1,501
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

Expert 100+
P: 449
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

Post your reply

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