473,756 Members | 1,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

invalid cast exception

Hi,
I've got a little problem with my C# WinForms test
application.
I would like to have a ComboBox showing a a visual value
and some hidden values.
So I build a class able to store thoose values. This class
called ListItem have got two private variable, one is a
string containing the visual value, the

other one is a UDT variable. It is a struct called
ValoriNascosti containing two variables a string and an
int.
The costructor of ListItem store the three values
(description, and the two of ValoriNascosti) . There is two
accessor methods that retrieve: the string of th

description; and another one retrieve a variable of type
ValoriNascosti.

I create an ArrayList of ListItem in this way:
ArrayList elencoProdotti = new ArrayList();
elencoProdotti. Add(new ListItem("0001" , 5, "Prodotto1" ));

I populate the combo with the ArrayList:
this.comboBox1. DataSource = elencoProdotti;

Than I tell to the combo that the member to display is
accessible from the method Descrizione:
comboBox1.Displ ayMember = "Descrizion e";
And the hidden value is accessible from the method
AccessorValoriN ascosti:
comboBox1.Value Member = "AccessorValori Nascosti" ;

Thoose two are the accessors I was talking about.

When I run this I've got my dear combo with the visual
data I've choose (like Prodotto1, Prodotto2, Prodotto3
etc...).

So I add code in the event SelectedIndexCh anged, trying to
show the hidden values when the combobox element changes.
So I do this:
this.textBox1.T ext = ((ValoriNascost i)
this.comboBox1. SelectedValue). moduli.ToString ();
but I've got an invalid cast exception.
This line give the same error:
ValoriNascosti supporto = (ValoriNascosti )
this.comboBox1. SelectedValue;
The value stored should be of valoriNascosti type... isn't
right this way of casting?
I really don't have clues. :-\
Thanks for help.
Giulio
Nov 15 '05 #1
3 13884
Hi Giulio,

What you have shown us looks correct to me, but there must be something
wrong somewhere. Have you tried just setting this.comboBox1. SelectedValue
into an object variable and looking at its actual type in the debugger. If
that doesn't help then could you show us some more code such as the
declarations of ListItem and ValoriNascosti.

Cheers

Doug Forster

"Giulio Santorini" <gi************ *************** ***@yahoo.it> wrote in
message news:07******** *************** *****@phx.gbl.. .
Hi,
I've got a little problem with my C# WinForms test
application.
I would like to have a ComboBox showing a a visual value
and some hidden values.
So I build a class able to store thoose values. This class
called ListItem have got two private variable, one is a
string containing the visual value, the

other one is a UDT variable. It is a struct called
ValoriNascosti containing two variables a string and an
int.
The costructor of ListItem store the three values
(description, and the two of ValoriNascosti) . There is two
accessor methods that retrieve: the string of th

description; and another one retrieve a variable of type
ValoriNascosti.

I create an ArrayList of ListItem in this way:
ArrayList elencoProdotti = new ArrayList();
elencoProdotti. Add(new ListItem("0001" , 5, "Prodotto1" ));

I populate the combo with the ArrayList:
this.comboBox1. DataSource = elencoProdotti;

Than I tell to the combo that the member to display is
accessible from the method Descrizione:
comboBox1.Displ ayMember = "Descrizion e";
And the hidden value is accessible from the method
AccessorValoriN ascosti:
comboBox1.Value Member = "AccessorValori Nascosti" ;

Thoose two are the accessors I was talking about.

When I run this I've got my dear combo with the visual
data I've choose (like Prodotto1, Prodotto2, Prodotto3
etc...).

So I add code in the event SelectedIndexCh anged, trying to
show the hidden values when the combobox element changes.
So I do this:
this.textBox1.T ext = ((ValoriNascost i)
this.comboBox1. SelectedValue). moduli.ToString ();
but I've got an invalid cast exception.
This line give the same error:
ValoriNascosti supporto = (ValoriNascosti )
this.comboBox1. SelectedValue;
The value stored should be of valoriNascosti type... isn't
right this way of casting?
I really don't have clues. :-\
Thanks for help.
Giulio

Nov 15 '05 #2
Hi,
I've put the comboBox1.Selec tedValue in an object variable
and in debug time, I've watch its type.

The application enter in the SelectedIndexCh anged two
times before I got the control.
Thoose two times the type of comboBox1.Selec tedValue is
ListItem. So is the entire class not just the
ValoriNascosti UDT.
The other times the type of comboBox1.Selec tedValue is
ValoriNascosti.
I've generate a piece of code that handle a cast invalid
exception and retrieve the value I need via accessor for
the first two time, and via the public value for the other
times.
Like this:
try
{
this.textBox1.T ext = ((ListItem)
this.comboBox1. SelectedValue). AccessorValoriN ascosti.moduli
..ToString();
this.textBox2.T ext = ((ListItem)
this.comboBox1. SelectedValue). AccessorValoriN ascosti.codice
Arte;
}
catch(InvalidCa stException)
{
this.textBox1.T ext = ((ValoriNascost i)
this.comboBox1. SelectedValue). moduli.ToString ();
this.textBox2.T ext = ((ValoriNascost i)
this.comboBox1. SelectedValue). codiceArte;
}
catch
{
MessageBox.Show ("Eccezione non gestita!");
}
Then it works. I've got what I need, but I still do not
understand why of the first two calls at
SelectedIndexCh anged. And why the type is ListItem just
the first two times. I've add five values at the ArrayList.

I put there the declaration of ListItem.
It will be bad formatted I hope a cut and past will make
it back as I've got it in Visual Studio.
-----------------------------------------------------------
---------THE CODE BEGIN------------------------------------
-----------------------------------------------------------

public class ListItem
{
/// <summary>
/// Contiene la descrizione del prodotto,
che verrà visualizzata nel controllo
/// </summary>
private string descrizione;
/// <summary>
/// E'una UDT che contiene i valori che
associati alla descrizione formeranno
/// un elemento nel controllo.
/// </summary>
private ValoriNascosti valoriNascosti;

/// <summary>
/// Il costruttore si occupa di generare
un nuovo oggetto con i valori passati.
/// </summary>
/// <param name="codiceArt e">codice
prodotto di arte elettrica</param>
/// <param name="moduli">n umero moduli che
compongono il prodotto</param>
/// <param name="descrizio ne">descrizio ne
del prodotto</param>
public ListItem(string codiceArte, int
moduli, string descrizione)
{
this.valoriNasc osti.codiceArte =
codiceArte;
this.valoriNasc osti.moduli =
moduli;
this.descrizion e = descrizione;
}

/// <summary>
/// Metodo accessor per ottenere la
variabile con i valori nascosti.
/// </summary>
public ValoriNascosti
AccessorValoriN ascosti
{
get
{
return this.valoriNasc osti;
}
}

/// <summary>
/// Metodo accessor al
valore "descrizion e".
/// Restituisco il valore descrizione.
/// </summary>
public string Descrizione
{
get
{
return this.descrizion e;
}
}

/// <summary>
/// Sovrascrivo il metodo restituendo i
valori che compongono l'oggetto.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return
this.valoriNasc osti.codiceArte + ' ' +
this.valoriNasc osti.moduli.ToS tring() + this.descrizion e;
}

}

public struct ValoriNascosti
{
public string codiceArte;
public int moduli;
}

-----------------------------------------------------------
---------THE CODE IS END-----------------------------------
-----------------------------------------------------------

Thanks for your help,
Giulio
-----Original Message-----
Hi Giulio,

What you have shown us looks correct to me, but there must be somethingwrong somewhere. Have you tried just setting this.comboBox1. SelectedValueinto an object variable and looking at its actual type in the debugger. Ifthat doesn't help then could you show us some more code such as thedeclarations of ListItem and ValoriNascosti.

Cheers

Doug Forster

"Giulio Santorini" <gi************ *************** ***@yahoo.it> wrote inmessage news:07******** *************** *****@phx.gbl.. .
Hi,
I've got a little problem with my C# WinForms test
application.
I would like to have a ComboBox showing a a visual value
and some hidden values.
So I build a class able to store thoose values. This class called ListItem have got two private variable, one is a
string containing the visual value, the

other one is a UDT variable. It is a struct called
ValoriNascosti containing two variables a string and an
int.
The costructor of ListItem store the three values
(description, and the two of ValoriNascosti) . There is two accessor methods that retrieve: the string of th

description; and another one retrieve a variable of type
ValoriNascosti.

I create an ArrayList of ListItem in this way:
ArrayList elencoProdotti = new ArrayList();
elencoProdotti. Add(new ListItem("0001" , 5, "Prodotto1" ));
I populate the combo with the ArrayList:
this.comboBox1. DataSource = elencoProdotti;

Than I tell to the combo that the member to display is
accessible from the method Descrizione:
comboBox1.Displ ayMember = "Descrizion e";
And the hidden value is accessible from the method
AccessorValoriN ascosti:
comboBox1.Value Member = "AccessorValori Nascosti" ;

Thoose two are the accessors I was talking about.

When I run this I've got my dear combo with the visual
data I've choose (like Prodotto1, Prodotto2, Prodotto3
etc...).

So I add code in the event SelectedIndexCh anged, trying to show the hidden values when the combobox element changes. So I do this:
this.textBox1.T ext = ((ValoriNascost i)
this.comboBox1. SelectedValue). moduli.ToString ();
but I've got an invalid cast exception.
This line give the same error:
ValoriNascosti supporto = (ValoriNascosti )
this.comboBox1. SelectedValue;
The value stored should be of valoriNascosti type... isn't right this way of casting?
I really don't have clues. :-\
Thanks for help.
Giulio

.

Nov 15 '05 #3
Hi Giulio,

That's very strange, but I guess you have a workaround. I have only used
SelectedItem myself and that always seems to return the correct type
(ListItem in your case)

Cheers

Doug Forster

"giulio santorini" <gi************ *************** *@yahoo.it> wrote in
message news:02******** *************** *****@phx.gbl.. .
Hi,
I've put the comboBox1.Selec tedValue in an object variable
and in debug time, I've watch its type.

The application enter in the SelectedIndexCh anged two
times before I got the control.
Thoose two times the type of comboBox1.Selec tedValue is
ListItem. So is the entire class not just the
ValoriNascosti UDT.
The other times the type of comboBox1.Selec tedValue is
ValoriNascosti.
I've generate a piece of code that handle a cast invalid
exception and retrieve the value I need via accessor for
the first two time, and via the public value for the other
times.
Like this:
try
{
this.textBox1.T ext = ((ListItem)
this.comboBox1. SelectedValue). AccessorValoriN ascosti.moduli
..ToString();
this.textBox2.T ext = ((ListItem)
this.comboBox1. SelectedValue). AccessorValoriN ascosti.codice
Arte;
}
catch(InvalidCa stException)
{
this.textBox1.T ext = ((ValoriNascost i)
this.comboBox1. SelectedValue). moduli.ToString ();
this.textBox2.T ext = ((ValoriNascost i)
this.comboBox1. SelectedValue). codiceArte;
}
catch
{
MessageBox.Show ("Eccezione non gestita!");
}
Then it works. I've got what I need, but I still do not
understand why of the first two calls at
SelectedIndexCh anged. And why the type is ListItem just
the first two times. I've add five values at the ArrayList.

I put there the declaration of ListItem.
It will be bad formatted I hope a cut and past will make
it back as I've got it in Visual Studio.
-----------------------------------------------------------
---------THE CODE BEGIN------------------------------------
-----------------------------------------------------------

public class ListItem
{
/// <summary>
/// Contiene la descrizione del prodotto,
che verrà visualizzata nel controllo
/// </summary>
private string descrizione;
/// <summary>
/// E'una UDT che contiene i valori che
associati alla descrizione formeranno
/// un elemento nel controllo.
/// </summary>
private ValoriNascosti valoriNascosti;

/// <summary>
/// Il costruttore si occupa di generare
un nuovo oggetto con i valori passati.
/// </summary>
/// <param name="codiceArt e">codice
prodotto di arte elettrica</param>
/// <param name="moduli">n umero moduli che
compongono il prodotto</param>
/// <param name="descrizio ne">descrizio ne
del prodotto</param>
public ListItem(string codiceArte, int
moduli, string descrizione)
{
this.valoriNasc osti.codiceArte =
codiceArte;
this.valoriNasc osti.moduli =
moduli;
this.descrizion e = descrizione;
}

/// <summary>
/// Metodo accessor per ottenere la
variabile con i valori nascosti.
/// </summary>
public ValoriNascosti
AccessorValoriN ascosti
{
get
{
return this.valoriNasc osti;
}
}

/// <summary>
/// Metodo accessor al
valore "descrizion e".
/// Restituisco il valore descrizione.
/// </summary>
public string Descrizione
{
get
{
return this.descrizion e;
}
}

/// <summary>
/// Sovrascrivo il metodo restituendo i
valori che compongono l'oggetto.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return
this.valoriNasc osti.codiceArte + ' ' +
this.valoriNasc osti.moduli.ToS tring() + this.descrizion e;
}

}

public struct ValoriNascosti
{
public string codiceArte;
public int moduli;
}

-----------------------------------------------------------
---------THE CODE IS END-----------------------------------
-----------------------------------------------------------

Thanks for your help,
Giulio
-----Original Message-----
Hi Giulio,

What you have shown us looks correct to me, but there must be somethingwrong somewhere. Have you tried just setting this.comboBox1. SelectedValueinto an object variable and looking at its actual type in the debugger. Ifthat doesn't help then could you show us some more code such as thedeclarations of ListItem and ValoriNascosti.

Cheers

Doug Forster

"Giulio Santorini" <gi************ *************** ***@yahoo.it> wrote inmessage news:07******** *************** *****@phx.gbl.. .
Hi,
I've got a little problem with my C# WinForms test
application.
I would like to have a ComboBox showing a a visual value
and some hidden values.
So I build a class able to store thoose values. This class called ListItem have got two private variable, one is a
string containing the visual value, the

other one is a UDT variable. It is a struct called
ValoriNascosti containing two variables a string and an
int.
The costructor of ListItem store the three values
(description, and the two of ValoriNascosti) . There is two accessor methods that retrieve: the string of th

description; and another one retrieve a variable of type
ValoriNascosti.

I create an ArrayList of ListItem in this way:
ArrayList elencoProdotti = new ArrayList();
elencoProdotti. Add(new ListItem("0001" , 5, "Prodotto1" ));
I populate the combo with the ArrayList:
this.comboBox1. DataSource = elencoProdotti;

Than I tell to the combo that the member to display is
accessible from the method Descrizione:
comboBox1.Displ ayMember = "Descrizion e";
And the hidden value is accessible from the method
AccessorValoriN ascosti:
comboBox1.Value Member = "AccessorValori Nascosti" ;

Thoose two are the accessors I was talking about.

When I run this I've got my dear combo with the visual
data I've choose (like Prodotto1, Prodotto2, Prodotto3
etc...).

So I add code in the event SelectedIndexCh anged, trying to show the hidden values when the combobox element changes. So I do this:
this.textBox1.T ext = ((ValoriNascost i)
this.comboBox1. SelectedValue). moduli.ToString ();
but I've got an invalid cast exception.
This line give the same error:
ValoriNascosti supporto = (ValoriNascosti )
this.comboBox1. SelectedValue;
The value stored should be of valoriNascosti type... isn't right this way of casting?
I really don't have clues. :-\
Thanks for help.
Giulio

.

Nov 15 '05 #4

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

Similar topics

5
3434
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS 5), but fails on IIS 6 running on a Win2003 server. The web uses Pages derived from a custom class I wrote (which itself derives from Page) to provide some common functionality. The Page_Load handler the failing webpage starts out like this: ...
9
2201
by: buzz | last post by:
I am attempting to pass data between two asp.net web forms pages. I have found the method to do this on the msdn site here: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconPassingServerControlValuesBetweenPages.asp After attempting to do this myself, I kept getting an Invalid Cast Exception error, so I finally resorted to simply copying and pasting the MS code in this article into two pages for the...
15
2253
by: David | last post by:
Hi, I have built a web application that will be a very high profile application. We had tested it, demonstrated it and shown that it all works. On a dress rehearsal run through, it failed spectacularly. I was so embarrassed and felt like killing the person that made it fail. However, when it goes live, IT MUST NOT FAIL. The system has a backoffice system that takes an excel spreadsheet from the
6
2612
by: cs_hart | last post by:
I am getting an invalid cast exception - cast from string to type double is not valid. Dim curName As String Dim prevName As String = "" curName = CStr(rows.Item(i).Item(colSchName)) ' extract name from database row If (curName.CompareTo(prevName <> 0)) Then <--- exception occurs on this line
7
3628
by: Chris Thunell | last post by:
I'm trying to loop through an exchange public folder contact list, get some information out of each item, and then put it into a vb.net datatable. I run though the code and all works fine until i get to item 250 i get a "system.invalid cast exception" and "specified cast is not valid". Once i get this error and try to go to the next record.. every record after gets the same error... It's like the com connection to outlook has been lost....
4
2303
by: Reticulated Ember | last post by:
I have the following code that fails with an invalid cast exception: .... System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage(); msg.BodyFormat = MailFormat.Html; msg.BodyEncoding = System.Text.Encoding.ASCII; msg.Attachments.Add(@"c:\banner.jpg");
0
1348
by: balukrishnan | last post by:
Hi... I am trying to create an object of Shdocvw.InternetExplorer class, using which I need to launch a particular URL(A JSP Webpage). Then I need to get the document of the page loaded. But while doing so, I encounter an Invalid cast exception for some properties of the document like frames, parent window, scripts and location. I also need to execute a script on this JSP. While doing so, this exception comes out. How can I overcome this?...
0
9455
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9271
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
9869
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...
0
9708
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
8709
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, and deployment—without 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
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3805
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
2
3354
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2665
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.