InvalidCastException when getting Text from a Label referenced by dynamicaly built String, Fix?

Posted by Chris on Stack Overflow See other posts from Stack Overflow or by Chris
Published on 2010-06-11T03:28:56Z Indexed on 2010/06/11 3:32 UTC
Read the original article Hit count: 274

Filed under:

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:

int c = 1; 
while (c < 251) 
{ 
string k = "l" + c.ToString(); //dynamic name of Control(Label) 
object ka = Controls.Find(k, true);  
string ct = ((Label)ka).Text;  //<<Error Occurs Here 
build = build + ct; 
c++; 
}

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".

© Stack Overflow or respective owner

Related posts about c#