473,402 Members | 2,055 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

InvalidCastException question

Hi all,
I have a form which has a TabControl and a Button. At runtime, on the
TabControl, I create a TabPage with a TextBoxes. Now, when I click the
button after entering some text in the textbox, I want to show the text in a
messagebox. I tried the following code but get an error.

foreach (System.Windows.Forms.TextBox myTextBox in myTabPage.Controls)
{
MessageBox.Show (myTextBox.Text);
}

The error I get is:-

"An unhandled exception of type 'System.InvalidCastException' occurred in
MyLib.dll

Additional information: Specified cast is not valid."

How do I get this right?

TIA,
Mounil.


Nov 17 '05 #1
7 2346
On Fri, 14 Oct 2005 09:59:13 +1000, MounilK wrote:
Hi all,
I have a form which has a TabControl and a Button. At runtime, on the
TabControl, I create a TabPage with a TextBoxes. Now, when I click the
button after entering some text in the textbox, I want to show the text in a
messagebox. I tried the following code but get an error.

foreach (System.Windows.Forms.TextBox myTextBox in myTabPage.Controls)
{
MessageBox.Show (myTextBox.Text);
}

The error I get is:-

"An unhandled exception of type 'System.InvalidCastException' occurred in
MyLib.dll

Additional information: Specified cast is not valid."

How do I get this right?


foreach (Control ctrl in myTabPage.Controls)
{
TextBox myTextBox = ctrl as TextBox;
if (myTextBox != null)
MessageBox.Show (myTextBox.Text);
}
--
Tom Porterfield
Nov 17 '05 #2
Your problem is this line:

foreach (System.Windows.Forms.TextBox myTextBox in myTabPage.Controls)

Several other programmers posting here have had the mistaken impression
that this means, "Loop through all of the TextBoxes on my TabPage." In
fact, it means "Loop through every control on my TabPage and attempt to
interpret every one of them as a TextBox."

If you have any control on your TabPage that is not a TextBox, the
foreach will bomb with an InvalidCastException, which is what you saw.

Tom Porterfield posted the correct solution.

Nov 17 '05 #3
Hi Tom,
Thanks a lot for your help.
--Mounil.

"Tom Porterfield" <tp******@mvps.org> wrote in message
news:1r***************@tpportermvps.org...
On Fri, 14 Oct 2005 09:59:13 +1000, MounilK wrote:
Hi all,
I have a form which has a TabControl and a Button. At runtime, on the
TabControl, I create a TabPage with a TextBoxes. Now, when I click the
button after entering some text in the textbox, I want to show the text
in a
messagebox. I tried the following code but get an error.

foreach (System.Windows.Forms.TextBox myTextBox in myTabPage.Controls)
{
MessageBox.Show (myTextBox.Text);
}

The error I get is:-

"An unhandled exception of type 'System.InvalidCastException' occurred in
MyLib.dll

Additional information: Specified cast is not valid."

How do I get this right?


foreach (Control ctrl in myTabPage.Controls)
{
TextBox myTextBox = ctrl as TextBox;
if (myTextBox != null)
MessageBox.Show (myTextBox.Text);
}
--
Tom Porterfield

Nov 17 '05 #4
foreach(Drawable d in drawableCollection)
{
System.Console.WriteLine(d.ToString());
}

Expands to:

System.Collections.IEnumerator enumerator= dc.GetEnumerator();
while (enumerator.MoveNext())
{

System.Console.WriteLine(((Drawable)(enumerator.Cu rrent)).ToString
());
}

with the potential for throwing a NullReferenceException or an
InvalidCastException.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #5
Hi Jeff,
Could you please elaborate on that.
Thanks,
Mounil.

Nov 17 '05 #6
Mounilk... you can think of foreach is as just a shorthand that the
compiler
understands and then "writes" code for you. so for your example:

foreach (System.Windows.Forms.TextBox myTextBox in myTabPage.Controls)
{
MessageBox.Show (myTextBox.Text);
}

you can think of the compiler rewriting your code to:

IEnumerator enumerator= myTabPage.Controls.GetEnumerator();
while (enumerator.MoveNext())
{
MessageBox.Show (((TextBox)enumerator.Current).Text);
}
There are two potential problems with this compiler "generated" code.
First is
the cast (TextBox)enumerator.Currrent. Unless every item in the
enumeration
is a TextBox, the cast will eventually fail since this is an "unsafe"
cast. This
will result in an InvalidCastException. The second problem is that an
item in
an enumeration may be null. You cannot safely invoke a method on a null
reference in C#. (Other languages let you send a message to a null
object by
the way.) This will result in a NullReferenceException. So you need to
do some
checking inside the foreach loop as Tom's code shows. I prefer to use is
because I think it is clearer coding.

An is expression evaluates to true if both of the following conditions
are met:
expression is not null.
expression can be cast to type. That is, a cast expression of the form
(type)(expression) will complete without throwing an exception.

So the code would look something like:

foreach (object o in myTabPage.Controls)
{
if (o is TextBox)
{
MessageBox.Show (((TextBox)o).Text);
}
// else do nothing and move on to next object
}

These pages may help:
http://www.geocities.com/Jeff_Louie/OOP/oop6.htm
http://www.geocities.com/Jeff_Louie/OOP/oop7.htm

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #7
Hi Jeff,
Thanks a lot for making things so clear. Really appreciate your
help.
--Mounil.
"Jeff Louie" <je********@yahoo.com> wrote in message
news:%2******************@TK2MSFTNGP09.phx.gbl...
Mounilk... you can think of foreach is as just a shorthand that the
compiler
understands and then "writes" code for you. so for your example:

foreach (System.Windows.Forms.TextBox myTextBox in myTabPage.Controls)
{
MessageBox.Show (myTextBox.Text);
}

you can think of the compiler rewriting your code to:

IEnumerator enumerator= myTabPage.Controls.GetEnumerator();
while (enumerator.MoveNext())
{
MessageBox.Show (((TextBox)enumerator.Current).Text);
}
There are two potential problems with this compiler "generated" code.
First is
the cast (TextBox)enumerator.Currrent. Unless every item in the
enumeration
is a TextBox, the cast will eventually fail since this is an "unsafe"
cast. This
will result in an InvalidCastException. The second problem is that an
item in
an enumeration may be null. You cannot safely invoke a method on a null
reference in C#. (Other languages let you send a message to a null
object by
the way.) This will result in a NullReferenceException. So you need to
do some
checking inside the foreach loop as Tom's code shows. I prefer to use is
because I think it is clearer coding.

An is expression evaluates to true if both of the following conditions
are met:
expression is not null.
expression can be cast to type. That is, a cast expression of the form
(type)(expression) will complete without throwing an exception.

So the code would look something like:

foreach (object o in myTabPage.Controls)
{
if (o is TextBox)
{
MessageBox.Show (((TextBox)o).Text);
}
// else do nothing and move on to next object
}

These pages may help:
http://www.geocities.com/Jeff_Louie/OOP/oop6.htm
http://www.geocities.com/Jeff_Louie/OOP/oop7.htm

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: WangHF | last post by:
hi , I had asked this question serveral days ago, but it's still unresolved. And I have found some new things. this error just occured sometimes,not always. the code like this:(It's running...
3
by: Max Bolingbroke | last post by:
Hi! I've run into a problem with my app, and I feel sure I'm missing something really basic! Essentially, I have a plugin architecture, so my main application searches a directory for DLLs,...
1
by: bob scola | last post by:
I have a csharp, VS 2003 solution for a winform application The application uses an object called a "matter" and the class is defined in matter.cs. I can load matter objects into a combobox ...
3
by: karunakar | last post by:
Hi All Here iam getting this Error "Specified cast is not valid." My Project has Onc solution diffrent class libarary In that solution DALfactory solution iam getting this error I was calling...
4
by: DOTNET | last post by:
Hi, Anybody help me regarding this error: I am assigning the values to the session variables when the button is clicked and passing these session variables to the next page and when I am...
0
by: QA | last post by:
I am using a Business Scorecard Accelarator in a Sharepoint Portal 2003 using SQL Server 2005 I am getting the following error: Error,5/7/2005 10:50:14 AM,580,AUE1\Administrator,"Specified cast is...
8
by: Gamma | last post by:
I'm trying to inherit subclass from System.Diagnostics.Process, but whenever I cast a "Process" object to it's subclass, I encounter an exception "System.InvalidCastException" ("Specified cast is...
4
by: rsdev | last post by:
Hi, I have an InvalidCastException which is completely puzzling me. I have checked all the members in the stored procedure against my data provider and seems to be ok. Also in the stack trace it...
8
by: Joe HM | last post by:
Hello - I was wondering that the "cleanest" way is to determine whether a CType() will throw an InvalidCastException? I have data I receive as an Object and I want to convert it to a String...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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 project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.