.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Post New Web Links


Posted By:      Posted Date: September 20, 2010    Points: 0   Category :.NET Framework


I am having base (INFO)Class with property




then cmo class will have two variables (eg name,____ with string datatype)

and i am having another base (response)class with property



public CMOSchedule[] CMOSCHEDULE

then CMOschedule class will have the same two varaibles (eg name,____ with string datatype)

I have an issue to when i cast



View Complete Post

More Related Resource Links

Problem casting date

I'm developing a Windows Forms app using VS 2008 with a SQL Server 2005 database. I've got search form where users can search for data by entering one or two criteria. One of these is a date which corresponds to a date field in my database. The user clicks on a button, which feeds the criteria into a stored procedure. The results are displayed in a datagridview control. While the functionality works well with the non-date criteria, whenever a date criteria is used on it's own a cast error is raised ('Conversion failed when converting datetime from character string.') I've tried lots of ways of casting the date (formatting using left, right and mid finctions, using the substring function etc) but still can't get it to work. Code and SQL are shown below. Does someone know where I've gone wrong? 'DateAssayRequested' is the date in question. <vb> 'set up and initialise connection conn = New SqlConnection(etc) comm = New SqlCommand comm.Connection = conn comm.CommandText = "SPSearch" comm.CommandType = CommandType.StoredProcedure 'create input parameters, set types and values param = comm.CreateParameter param.ParameterName = "@assayid" param.Direction = ParameterDirection.Input param.Value = txtLabNo.Text

How to: Deal with UniqueIdentifiers, casting it to Guid in DAL

HelloMy users table has a column which is a unique identifier (basically this has FK relationship with aspnet_users table, of membership) Now I have an AppUser class which maps to my users tableuserid        intuser_aspnet_id  guid In my DAL, I am retreiving a user from the db an want to populate my appUser obj. How do i Convert value retreived to GuidappUsr.UserID = Convert.ToInt32(reader["user_id"]);appUsr.AspNetUserID =  reader["aspnet_user_id"];(There is no convert.ToGuid)How can this be done?appUsr.UserID = Convert.ToInt32(reader["user_id"]);                 appUsr.AspNetUserID = (Guid)reader["aspnet_user_id"];

IEnumerable Type Casting

Hello Everyone,  The following line is giving me an InvalidCastException when trying to convert to IEnumerable type, even though I have implemented IEnumerable interface.  Return New CountryInfo(CountryCodes(i), CountryNames(i)) (also in bold below)Imports System Imports Gaia.WebWidgets.HtmlFormatting Imports System.Collections.Generic Imports System.Globalization Public Class CountryInfo Implements IEnumerable Property Name As String Property Code As String Public Sub New(ByVal code As String, ByVal name As String) _Code = code _Name = name End Sub Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return CType(Me, IEnumerator) End Function Public Class SearchResult Private ReadOnly _countries As List(Of CountryInfo) Private ReadOnly _query As String Friend Sub New(ByVal countries As List(Of CountryInfo), ByVal query As String) _countries = countries _query = query End Sub Public ReadOnly Property IsEmpty As Boolean Get Return _countries.Count = 0 End Get End Property Public ReadOnly Property Countries As List(Of CountryInfo) Get Return _countries End Get End Property Public Function Bui

Casting issues when using WHERE and uniqueidentifier

Hello all, I am getting the same error when trying to build the queries below by using 2 diffferent methods: DECLARE @stepIds varchar(8000), @instance uniqueidentifier, @instance_binary binary(16) SET @stepIds = '' SET @instance = '28B2D4FB-67F6-40CA-84A2-839BF3CC4B91' SET @instance_binary = CAST(@instance AS binary(16)) SELECT @stepIds = @stepIds + ',''' + stepID + '''' from Uds.RealtimeLogging WHERE instanceID = @instance_binary --Conversion failed when converting the varchar value ''' to data type int. --OR DECLARE @stepIds varchar(8000), @instance uniqueidentifier SET @stepIds = '' SET @instance = '28B2D4FB-67F6-40CA-84A2-839BF3CC4B91' SELECT @stepIds = @stepIds + ',''' + stepID + '''' from Uds.RealtimeLogging WHERE instanceID = convert(uniqueidentifier, @instance) --Conversion failed when converting the varchar value ''' to data type int. Thank you  JCD

Bitmap casting

Hi, I'm working on a project that manipulate images. I put a Open Dialog Box to load images to the program. After the user choose an especific image my program does something like this: pictureBox1.Image = (Bitmap)image; It works fine with all image format I've tested. Will it work for all image formats? Thanks.

Weird casting error (storing Generic list in Session)


Am trying to store a generic list in Session to act as a simple shopping cart. Am getting a weird casting error when I try and retrieve it from Session.

A critical error has occurred.
[A]System.Collections.Generic.List`1[MyCartItem] cannot be cast to [B]System.Collections.Generic.List`1[MyCartItem].
Type A originates from 'mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'
    in the context 'LoadNeither' at location 'C:\WINDOWS\assembly\GAC_32\mscorlib\\mscorlib.dll'.
Type B originates from 'mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'
    in the context 'LoadNeither' at location 'C:\WINDOWS\assembly\GAC_32\mscorlib\\mscorlib.dll'.

I have a class variable defined:

List<MyCartItem> _cart;

In the Load event I have:

_cart = (Session["MyCart"] != null) ? (List<MyCartItem>)Session["MyCart"] : new List<MyCartItem>();

Dynamic Generic Casting


Hi guys

I am wanting to do some dynamic casting/variable creation with some generics but am having a little trouble. Essentially, the type of the generic need to be the same as a given variable. As such a simple example would be something like this but obviously it doesn't work:


Code Block

int value = 10;

Type type = value.GetType();

List<type> list = new List<type>();


The exmaple that i have is something like this:

How do I check if ExecuteScalar() returned me any rows when you are using casting this way...


Hi all

The code below works fine if I have records on my table but if the table is empty I get the following error:

latestTimeStamp1 = (DateTime)cmd.ExecuteScalar(); <=== {"Specified cast is not valid."}

So I am trying to add an IF statement to check if there was any return from ExecuteScalar() method.
How can I verify if something was returned or how can I prevent this cast error from happening?
I managed a workaround by using DataTable and checking if table was null but I need this code to have less overhead as possible since I will be pulling up this timeStamp date all the time.

 DateTime latestTimeStamp1 = DateTime.UtcNow;
 string select = "select max(timeStamp) from Table1";

 SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Test"].ConnectionString);
		 SqlCommand cmd = new SqlCommand(select, conn);

	//if ExecuteScalar returns something 
	 	latestTimeStamp1 = (DateTime)cmd.ExecuteScalar();
		return latestTimeStamp1;
 catch (Exception ex)

Thank you

Generic Casting to access Text property


I have a situation where I'm iterating through all the controls on a form, specifically looking out for any of these three types of controls:  Labels, TextBoxes, CheckBoxes

I can, of course, get the type of the control and then use a Switch-Case construct to cast labels as Labels, textboxes as TextBoxes, and checkboxes as CheckBoxes.

But I'm wondering if there's a way to do something with one or two lines of code to gain access to the Text property of each of these controls?

I'm guessing this isn't possible but thought I'd ask to be sure,


Casting transparent proxy of office application to the real object



1. I am using .net remoting to accept an office application (Excel,Word,PP)

2. the server is a simple office addin that supplies the application object

3. the remote object is application object wrapper (to enable MarshalByRefObject inheritance)

4. When the client gets the application object its type is Proxies.__TransparentProxy for all 3 applications

5. The problem is when trying to cast the transparent proxy to the real objects types

Microsoft.Office.Interop.PowerPoint.Application for PP

Microsoft.Office.Interop.Word.Application for Word

Microsoft.Office.Interop.Excel.Application for Excel

 the cast fails for Word  and PP whereas for Excel it works perfect

6. Since I also own the server code (the office addin) I can check what is the application

Datatype casting/conversion



I am working on updating an existing ASP.NET server-side application using VS2008 and DOT-NET 3.5 Framework.   I come from a primarily VB/VB.NET/SQL background.


We have added a third-party custom control to the application.


I try assigning the .VALUE property (type decimal) to a variable of type decimal and I get this error:

"Cannot implicitly convert type 'object' to 'decimal'. An explicit conversion exists (are you missing a cast?)" 

That is the exact text from the error.  (Its aparently recoginizing the control.value as an 'object' and not a 'decimal' as it was intended.)


So I then try going a cast but its returning a different error saying "'Decimal' is not recognized"


How does one do casting or datatype conversion (or both) in C#?


Question regarding casting and as keyword



I have a question regarding casting that usually we do and the "as" keyword in C#.

E.g. in my code I use the following:

int counter = (int)strReturnValue;


Or I can also use the following:

int counter = strReturnValue as int;


Is there any difference between the above lines of code? As per my understanding if we use "as" keyword, it may not throw exception if the value in strReturnValue variable cannot be casted to int.

Please correct me if I am wrong. 

Error Casting to XML Data Type


I have an Ntext data type column, with 2000 XML Documents in it, I am trying to Cast(Col as Xml)

It is casting few of them and then failing.

Error: XML Parsing: Line10, character 6, well formed check: undeclared entry

I want to know if there is any way to write a query to find all Non Formed XML Documents?

Thanks loadsss in advance.

Problem with Casting from XML to Varchar(max)



I am facing problem with casting from XML to varchar(max). I declared one variable as XML and that variable contains data in XML format and it contains more than 8000 chars (in our application some times it may contains nearly 100000 also).

Now, I am trying to cast that XML type variable to varchar(max), on that time varchar(max) variable taking 8000 chars only. I need all chars what XML variable contains into varchar(max) variable.

For easily reference, below is my code.


DECLARE @ParameterSQL AS VARCHAR(MAX) = 'Select Top 50 * from Certificates ' 




DECLARE @Paramlist NVARCHAR(1000)

SET @Paramlist = N'@XML XML OUTPUT'

SET @SQL = 'WITH PrepareTable (XMLString) '

SET @SQL = @SQL + 'AS ( '


SET @SQL = @SQL + ') '

SET @SQL = @SQL + 'SELECT @XML = XMLString FROM PrepareTable '

EXEC sp_executesql @SQL, @Paramlist, @XML=@XML OUTPUT





Actually, the @xml contains more than 8000 chars, but @XMLString contains only 8000 chars after casting.

I tried in this way, SET @XMLString = CAST(@XML AS VARCHAR(15000)). This time i am getting error l

casting to complex type


I'm trying to figure out how to use the combobox item object collection.  Given the code below, how can I put a term in the "Cast<?>" statement to get my anonymous types back?  Or, is there a completely different way to do it?  Can I explicitly cast 'a'?

var citiesbox = new ComboBox();
ComboBox.ObjectCollection objects_to_store = new ComboBox.ObjectCollection(citiesbox);
objects_to_store.Add(new { cityid = 1, cityname = "Eugene" });
objects_to_store.Add(new { cityid = 2, cityname = "Portland" });
objects_to_store.Add(new { cityid = 3, cityname = "Salem" });

var citycode_from_db = 2;

citiesbox.SelectedItem = from a in citiesbox.Items.Cast<?>
             where a.cityid = citycode_from_db
             select a;
-Ethan Nelson

Dynamic Explicit Casting


I have the following C# code in a method of a class that inherits from Image. Basically I'm setting a random left margin (within some parameters) relative to its container (a Grid object).

int auxLeftMargin = rand.Next(Convert.ToInt32( ((Grid)Parent).ActualWidth / 4), Convert.ToInt32(((Grid)Parent).ActualWidth - ((Grid)Parent).ActualWidth / 6));

Margin = new Thickness(auxLeftMargin, Margin.Top, Margin.Right, Margin.Bottom);

I've changed the container type a couple of times already, so I would like to be able to not have it hardcoded. I've tried casting with "( Parent.GetType() )" but it doesn't work.

Is there a way to do this dynamically? Thanks.

Casting byte array to structure in C# -- Exception thrown



     I am using the below function to cast the byte array to the structure.But when i do that i am getting an exception saying"Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Please help me on this ASAP.

   public VasConfig BytetoStructure(byte[] bff)
     GCHandle pinnedPacket = GCHandle.Alloc(bff, GCHandleType.Pinned);
     VasConfig vasconfig = (VasConfig)Marshal.PtrToStructure(
    return vasconfig;

Structure is as below
#region Vas Data Structure
//Vas Commands used for communication between PC client to DSP server
using System.Runtime.InteropServices;
public enum VasCommands

//This is used for identifying the first data buffer
public enum yuv_fmt
  Y = 5,
//Video formats 
//Video formats 

public enum VideoFormat
  YUV_420 = 15,

//Data stream types: Currently only video is supported

public enum DataTypes
  VIDEO = 1,

//Error Code definitions

public enum ERROR_CODE
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend