Windows Develop Bookmark and Share   
 index > Windows Forms Designer > Unable to cast object of type 'X' to type 'X'
 

Unable to cast object of type 'X' to type 'X'

The actual projects structure is:
+ MyServerFramework
|---QueryComponent.cs
...
+ MyServerFramework.Design
|---QueryComponentDesigner.cs
...

The MyServerFramework.Design project has a reference to MyServerFramework, and is compiled alone in its own solution which also contains MyServerFramework, and then placed in a folder that is referenced the SOFTWARE\Microsoft\.NETFramework\AssemblyFolders key so the IDE can find it.

The MyServerFramework project is then used in other solutions which don't contain the MyServerFramework.Design assembly. And here is where I'm seeing this error.

This happens in the following line, which is in the verb handler in QueryComponentDesigner:

QueryBuildStorProcDialog dlg = new QueryBuildStorProcDialog((QueryComponent)this.Component);

I've checked this at runtime with the debugger and this.Component IS of type QueryComponent.

Since it can't cast an object of a type to EXACTLY THE SAME TYPE, I guess either the error message is wrong or the problem lies in some versioning problem. Neither of the assemblies are strong-named, and I've tried changing the reference method: adding MyServerFramework.Design to the solution and referencing it as a project, referencing it by file name (Browse... in the add reference dialog), and adding it to the AssemblyFolders folder).

Is it possible the IDE is caching a previous version of my .Design assembly and using it instead of the current one (that it should find through the reference in the project or in the AssemblyFolders folder?

Juan Ignacio Gelos  Tuesday, December 13, 2005 12:42 PM

I just can't believe there's noone at Microsoft being able to answer these questions, I just hope they are busy trying to come up with some solutions to the myriad of problems in VS2005.

This particular problem apparently arises because of several factors:
The IDE caches versions of assemblies in the following folder:

"x\Documents and Settings\user\Local Settings\Application Data\Microsoft\VisualStudio\8.0\ProjectAssemblies"

And at least in my case doesn't detect the particular assembly containing the type has a new version and it doesn't update the cache.

If you attach to a running instance of VS2005 and check what Modules are loaded (you may need to add the Modules window command from the Debug category in Tools > Customize...) you'll probably see two versions of your assembly are loaded, or even the same version of the assembly loaded twice: in both cases you'll see the same error message.

So first step, delete all folders in ProjectAssemblies. Next, make sure the IDE can only find ONE copy of your assembly, which is easier if you only have one copy of the DLL in your disk, and only one reference to it (or exactly the same reference from all projects) in your solution.

 

Juan Ignacio Gelos  Thursday, December 15, 2005 3:01 AM
Jelle van der Beek2  Tuesday, December 13, 2005 4:07 PM

I just can't believe there's noone at Microsoft being able to answer these questions, I just hope they are busy trying to come up with some solutions to the myriad of problems in VS2005.

This particular problem apparently arises because of several factors:
The IDE caches versions of assemblies in the following folder:

"x\Documents and Settings\user\Local Settings\Application Data\Microsoft\VisualStudio\8.0\ProjectAssemblies"

And at least in my case doesn't detect the particular assembly containing the type has a new version and it doesn't update the cache.

If you attach to a running instance of VS2005 and check what Modules are loaded (you may need to add the Modules window command from the Debug category in Tools > Customize...) you'll probably see two versions of your assembly are loaded, or even the same version of the assembly loaded twice: in both cases you'll see the same error message.

So first step, delete all folders in ProjectAssemblies. Next, make sure the IDE can only find ONE copy of your assembly, which is easier if you only have one copy of the DLL in your disk, and only one reference to it (or exactly the same reference from all projects) in your solution.

 

Juan Ignacio Gelos  Thursday, December 15, 2005 3:01 AM

The story is not new -- this is the same behaviour as in 2002/2003. An additional source of problems is the "Local Copy" property of references: Even if the same dll is copied and then loaded from a different location, its types differ from those of the original dll.

Just make a test: At the point where the types are found to be different compare _all_ their attributes (after all types are just objects and they can differ only if their attributes differ). Print them out. You will see exactly the difference, that matters.

HTH,

D.Raiko

 

DRaiko  Thursday, December 15, 2005 8:32 AM

Yes, I don't recall having this problem with the ProjectAssemblies folder, but then again I didn't work too much on the design-time area... was it there too?

In any case, I think this is aggravated on 2005 because they also automatically add components in projects to the toolbar, which I suspect adds another binding to the cache or another cache alltogether, augmenting the chances of caching an old version.

I wonder if they do the correct thing in the DataSources window model or we have the same problems there...

Juan Ignacio Gelos  Thursday, December 15, 2005 12:21 PM

I had the"unable to cast from x to x" error when the designer tried to load my main form which contained acustom control. If I simply put the cast within a try-catch block, everything worked fine. Note, the code never hit the catch block, so i don't know why that hack works, but it has held up so far.

-Tony

tony_held@yahoo.com

Tony Held  Saturday, April 08, 2006 2:26 AM

Hi and THANKS a lot in advance.

I'm getting this error in a different scenario, and I'm in a big urge to get this done, so please MS people and guys of the forum, any help is greatly appreciated.

I'll use a simplified scenario of my case, but the error happens the same. I'm creating a new User Control, I add a DataGridView to it, that's the only control in it.  I then create a public property called "Columns" to expose the DataGridView Columns property so I can access the property to the Desingner Editor.  I do that this way:

namespace WindowsApplication3
{
    public partial class myUC : UserControl
    {
        public myUC()
        {
            InitializeComponent();
        }

        [Editor("System.Windows.Forms.Design.DataGridViewColumnCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
        [MergableProperty(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public DataGridViewColumnCollection Columns
        {
            get { return this.dataGridView1.Columns; }
        }
    }
}

I took all that Attributes code from the System.Windows.Forms.DataGridView metadata, just as the Columns property appears in it.

Then, I add a Windows Forms item to my application and drag&drop one MyUC control from the toolbox into it.  Then I click the MyUC and go to its properties page to modify the Columns properties just as with an ordinary DataGridView.  The property is there but when clicking on its "..." button to open de Edit Columns Dialog I get the mentioned error.  Something like this:

"Unable to cast object of type 'WindowsApplication3.myUC" to type "System.Windows.Forms.DataGridView".

I tried what you have mentioned but it doesn't work. I still get this error.

I really really need the Columns property to be accesible in Desing Time this way.  I don't know how to work this out.

As I said, I get this error with an almost blank project.  Just add a User Control Item, put a DataGridView into it. Ade the code above to make the Columns property visible and then try to access the property in the Property page. 

Thank you so much in advance.

Fernando.

 PD: I'm using the shipped VS.NET 2005.

 

Laquesis  Friday, April 21, 2006 10:48 PM
Anyone? Please.
Laquesis  Tuesday, April 25, 2006 9:25 PM
The problem is often that the assemblies are in a different directory. All you have to do is set all of the build output paths to the same folder. That way there will only be one copy of the dll. Then delete all of the old bin directories. This is much more like the environment after installation so this is perfectly valid. Worked for me, YMMV.
mdritchie  Tuesday, June 06, 2006 3:29 PM
public DataGridViewColumnCollection Columns

It's a read-only property by the way you defined your property.
JRQ  Friday, June 09, 2006 3:51 PM
Try this

QueryComponent comp = (QueryComponent)this.Component;
QueryBuildStorProcDialog dlg = new QueryBuildStorProcDialog(comp);
JRQ  Friday, June 09, 2006 3:55 PM
I have no idea why it makes a difference that they're in different directories, but unifying the build paths for my projects into a single bin\ directory did indeed fix the problem. So add another vote for the single build directory solution.
WaldenL  Monday, July 31, 2006 4:15 PM
Hello,

The problem persists. Is this a bug? How to reproduce?
- Create C# class library project
- Add usercontrol : MyGridControl
- Add a DataGridView control to the user control.
- Add a public property "ABC" to the user control,
public DataGridViewColumnCollection ABC
{
get { return datagridView1.Columns;}
}
- Add a public property "XYZ" to the user control,
public DataGridView XYZ
{
get { return datagridView1;}
}

- In another (winforms) project, add the previous assembly to the toolbox
- Drag the "MyGridControl" component to the Winform
- In the designer, try to edit the ABC property => errors
- In the designer, try to edit XYZ.Columns property => NullReferenceException.

Please advice...


iceman4  Monday, October 30, 2006 4:23 PM
Theproperties that you defined are read-only that's why the designer is complaining.
JRQ  Monday, October 30, 2006 10:43 PM
You can enter a blank line in your master page, then delete it, rebuild your program and your code should work after that.

This will work.

Kataria Bipin
Kataria Bipin  Wednesday, February 14, 2007 12:38 PM
A simple one I've had happen to me that threw the cannot cast Type X to Type X error went someting like:

.
.
using X;
.
.


namespace X
{
.
.


This can cause the self-cast error (although it will not always throw it). Of course this is the simple case, it could be a double-reference between more than one class.


Ryan Black  Monday, October 29, 2007 6:47 PM
Thanks! Kataria Bipin

I'm WPF developer, got the same problem
Your solution worked fine for me !
GiggsWalk  Saturday, January 19, 2008 1:49 AM

There are two main causes,

  1. Miss References, ie referencing one and IDE loding different or something like that, due to different version of COM object loaded in Registry from different location.
  2. Threading: Some COM dont support threading. So remove that class from any threading and test in console application. We will know the reason.

Rudra Poudel
Elvsys
Rudra Poudel  Wednesday, February 20, 2008 8:36 AM

Hi, I encounter exactly the same problem with VS 2008 (C#).

Without the attributes, the designer to change the columnswill open but not save the changes in the code.

With the attributes, I get the 'Can not cast'-error.

Did you ever find a solution for this problem? Thanks for your answer!!!

Karsten

[Editor("System.Windows.Forms.Design.DataGridViewColumnCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]

[MergableProperty(false)]

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]

public DataGridViewColumnCollection DataGridColumns

{

get { return MyDataGrid.Columns; }

}

Karsten Boehler  Thursday, March 06, 2008 4:41 PM

Close your VS2005 IDE windows. Start/Run "IISRESET" and this problem should go away. Mine did.

Fishersman  Monday, March 10, 2008 6:57 PM
i put all the build output of every project to the same folder...and it didnt fix.. now im trying to restart iis so the configurations can take place but.
it says windows cannot find 'IISRESET' .. i looked for iisreset.exe but no file found...

my error is:
An error occurred creating the form. See Exception.InnerException for details. The error is: Unable to cast object of type 'System.ComponentModel.Container' to type 'System.Type'.

what can i do to fix this?
ragekc  Wednesday, April 30, 2008 7:37 PM

hi I Load Report.Rdlc into XMLDocument and Save it(in XML). it Save Successfully but when I read that XML it shows

{"The table (ReportItems) cannot be the child table to itself in nested relations."} Error.how could I solve?. it's urgent. My main Objective is I want to Customize Rdlc. I want to display Column(s) on the user's choice. Suppose I have 10 Columns. I want to give rights to user that how many column he want to display on theReport

XmlDocument rdlcXML = new XmlDocument();

try

{

FileStream streamingReport = new FileStream(Server.MapPath("Report.rdlc"), FileMode.Open);

try

{

rdlcXML.Load(streamingReport);

}

finally

{

streamingReport.Close();

}

XmlNodeList typeNodeList = rdlcXML.GetElementsByTagName("Type");XmlNode typeNode = typeNodeList[0];

DataSet1TableAdapters.CustomersTableAdapter da = new DataSet1TableAdapters.CustomersTableAdapter();

ReportDataSource rptdsDepartmentWiseLateDetails = new ReportDataSource("DataSet1_Customers", da.GetData());

ReportViewer1.LocalReport.DataSources.Add(rptdsDepartmentWiseLateDetails);

ReportViewer1.LocalReport.LoadReportDefinition(
new StringReader(rdlcXML.OuterXml));

ReportViewer1.LocalReport.Refresh();

XmlNode node;

node = rdlcXML.DocumentElement;

rdlcXML.Save(
@"C:\ss.xml");

DataSet ds = new DataSet();ds.ReadXml(@"C:\ss.xml"); //Error on this Line

DataGrid1.DataSource = ds;

DataGrid1.DataBind();

}

finally

{

}

Rastogi  Thursday, May 22, 2008 6:08 AM
I hate to be so dumb, but where is the code where you unified the build paths for your projects into a single bin\ directory. What did you write? Or what did you erase? Is it in the web.config file, some *.aspx.vb files or where?

mhh12  Tuesday, June 24, 2008 8:13 PM
Hola, para evitar este error se debe hacer lo siguiente:

Hacemos un control que herede siempre del control original:

Asi

Imports System.ComponentModel

Public Class UserControl1

Inherits DataGridView

Private _grid As New DataGridView()

Private _alfa As New System.Windows.Forms.DataGridViewColumnCollection(_grid)

<Editor("System.Windows.Forms.Design.DataGridViewColumnCollectionEditor, System.Design", GetType(System.Drawing.Design.UITypeEditor))> _

Public ReadOnly Property Alfa() As System.Windows.Forms.DataGridViewColumnCollection

Get

Return _alfa

End Get

End Property

End Class


Con esto funcionara si o si. en comparacion conla propiedad columns para que se note la diferencia.

Para apreciarlo usa un control property para verlo en modo de ejecucion.

Para ver que funciona

Atte,

Angel Garin Morales.
Angel Garin Morales  Monday, December 29, 2008 2:06 AM
I have a same issue but it was for objects im not creating the error is below...


Unable to cast object of type 'System.ServiceModel.Configuration.ServiceHostingEnvironmentSection' to type 'System.ServiceModel.Configuration.ServiceHostingEnvironmentSection'.
Debradshaw  Wednesday, February 11, 2009 4:25 PM

Hi, I encounter exactly the same problem with VS 2008 (C#).

Without the attributes, the designer to change the columnswill open but not save the changes in the code.

With the attributes, I get the 'Can not cast'-error.

Did you ever find a solution for this problem? Thanks for your answer!!!

[Editor("System.Windows.Forms.Design.DataGridViewColumnCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]

[

MergableProperty(false)]

[

DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]

public DataGridViewColumnCollection DataGridColumns

{

get { return MyDataGrid.Columns; }
}



Hi Guys,
I've met the same problem. Has anyone found solution?
PashkaTLT  Wednesday, September 16, 2009 2:21 PM

You can use google to search for other answers

Custom Search

More Threads

• Design time support for protected property
• User Control That Could Contain Controls Dragged On It At Design Time
• Easy Question: new Table() and new Label()
• this.Refresh(); problem in C#
• Text Location in C# Label control .NET forms mysterious padding????
• "AutoSize" and "AutoSizeMode" usage
• User controls VB 2005 vs vb 6 "Property Pages"
• drop down menu in DataGridView
• cant open the project in VS due to user control error at design time
• Best way to substitute customized datagridview for standard datagridview??