How do I get around this error "Unable to cast object of type 'System.DBNull' to type 'System.String' "

I am using Visual Developer 2008 Express Edition for the first time, and I keep getting the following error below. The site allows anyone to enter with a valid username and password, but even when I logoff the site I get the same error....like the memory or database is not getting refreshed. I would think that when I initially compile the site that anything left in memory would be flushed out. Can someone please help me to figure this out.

Thanks,

Ramell P.S. The site is programmed using C# 

 

Unable to cast object of type 'System.DBNull' to type 'System.String'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.

Source Error:

Line 57: }
Line 58: 
Line 59: 		                        <asp:Label ID="Label2" runat="server" Text='<%# SharedRoutines.truncate((string)Eval("description")) %>' />
Line 60: 								<a href='<%# "News_View.aspx?Articleid=" + Convert.ToString(Eval("ID")) %>'>read more
Line 61: 									&raquo;</a>

Source File: e:\Web Site Portfolio\Greater_Mt_Olive\WebPartControls\RecentNews.ascx    Line: 59

Stack Trace:

[InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.]
   ASP.webpartcontrols_recentnews_ascx.__DataBinding__control8(Object sender, EventArgs e) in e:\Web Site Portfolio\Greater_Mt_Olive\WebPartControls\RecentNews.ascx:59
   System.Web.UI.Control.OnDataBinding(EventArgs e) +99
   System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +206
   System.Web.UI.Control.DataBind() +12
   System.Web.UI.Control.DataBindChildren() +204
   System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216
   System.Web.UI.Control.DataBind() +12
   System.Web.UI.WebControls.Repeater.CreateItem(Int32 itemIndex, ListItemType itemType, Boolean dataBind, Object dataItem) +130
   System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) +454
   System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) +53
   System.Web.UI.WebControls.Repeater.DataBind() +72
   System.Web.UI.WebControls.Repeater.EnsureDataBound() +55
   System.Web.UI.WebControls.Repeater.OnPreRender(EventArgs e) +12
   System.Web.UI.Control.PreRenderRecursiveInternal() +86
   System.Web.UI.Control.PreRenderRecursiveInternal() +170
   System.Web.UI.Control.PreRenderRecursiveInternal() +170
   System.Web.UI.WebControls.WebParts.WebPart.PreRenderRecursiveInternal() +62
   System.Web.UI.Control.PreRenderRecursiveInternal() +170
   System.Web.UI.Control.PreRenderRecursiveInternal() +170
   System.Web.UI.Control.PreRenderRecursiveInternal() +170
   System.Web.UI.Control.PreRenderRecursiveInternal() +170
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2041

 

0
ramelllamar
1/23/2008 3:26:53 AM
asp.net.getting-started 91979 articles. 4 followers. Follow

3 Replies
4057 Views

Similar Articles

[PageSpeed] 24
Get it on Google Play
Get it on Apple App Store

Change your binding code like so

 

<asp:Label ID="Label2" runat="server" Text='<%# SharedRoutines.truncate(Eval("description").ToString()) %>' />
 

I believe using ToString instead of casting to a string will return an empty string for DBNull. There is no quick way for me to test this though. If that doesn't work you can set the value using a conditional like so... 

 

SharedRoutines.truncate(   (Eval("description")  == System.DBNull)? "" : Eval("description").ToString() );
 
Basically if DBNull, return empty string else continue. 
 

Hope this helps. 

0
triggered
1/23/2008 3:43:25 AM

FYI, it looks like this code...

(string)Eval("description")

...is failing because "description" is null.

How to fix that?

I am sorry; but, I do not know the code-infront declarative syntax.

In code-behind, it would be something  like this...

        //Get the value from the database.       
        string myValue = "";

        if (myValue == DBNull.Value)
        {
            //The value is null and I cannot do this...
            //(string)Eval("description")
        }
        else
        {
            //The value is not null and I can do this...
            //(string)Eval("description")
        }
 


http://www.NetBrainer.com
0
mkamoski
1/23/2008 3:50:20 AM
This works...thanks very much. Now I have a new Problem....I'm getting the error message below when I log out of my site (with my username and password), and try to click on any other link afterwards. I notice that there is a temp file that is being referenced on my local drive (c:\Users\Ramell\AppData\Local\Temp\Temporary ASP.NET Files\greater_mt_olive\a7f156ac\57ce8d6c\App_Code.uozotu5o.9.cs). I would assume that the data base connection is trying to reference this temp file to determine the user ID, as opposed to just looking at the user ID in real-time once I have logged off the site. Is there some way that I can get around this? 

How can I program the site to reset it self once anyone log out of the site? 

Thanks,

Ramell   

Cannot open database "ClubDB" requested by the login. The login failed.
Login failed for user 'Ramell-PC\Ramell'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Cannot open database "ClubDB" requested by the login. The login failed.
Login failed for user 'Ramell-PC\Ramell'.

Source Error:

Line 2186:            this.Adapter.SelectCommand = this.CommandCollection[0];
Line 2187:            DataSet.SiteSettingsDataTable dataTable = new DataSet.SiteSettingsDataTable();
Line 2188:            this.Adapter.Fill(dataTable);
Line 2189:            return dataTable;
Line 2190:        }

Source File: c:\Users\Ramell\AppData\Local\Temp\Temporary ASP.NET Files\greater_mt_olive\a7f156ac\57ce8d6c\App_Code.uozotu5o.9.cs    Line: 2188

Stack Trace:

[SqlException (0x80131904): Cannot open database "ClubDB" requested by the login. The login failed.
Login failed for user 'Ramell-PC\Ramell'.]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +800131
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +186
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1932
   System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +33
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +172
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +381
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +181
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +173
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +357
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +30
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +424
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
   System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +494
   System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +82
   System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +105
   System.Data.SqlClient.SqlConnection.Open() +111
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +121
   System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior) +162
   System.Data.Common.DbDataAdapter.Fill(DataTable dataTable) +107
   DataSetTableAdapters.SiteSettingsTableAdapter.GetSiteSettings() in c:\Users\Ramell\AppData\Local\Temp\Temporary ASP.NET Files\greater_mt_olive\a7f156ac\57ce8d6c\App_Code.uozotu5o.9.cs:2188
   DevCowSiteSettings.GetSiteSettings() in e:\Web Site Portfolio\Greater_Mt_Olive\App_Code\SiteSettings.cs:49
   DevCow.Web.UI.DevCowThemePage.Page_PreInit(Object sender, EventArgs e) in e:\Web Site Portfolio\Greater_Mt_Olive\App_Code\DevCowThemePage.cs:20
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
   System.Web.UI.Page.OnPreInit(EventArgs e) +2062504
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +663


Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

0
ramelllamar
1/24/2008 2:52:17 AM
Reply:

Similar Artilces:

Update error , "Unable to cast object of type 'System.DBNull' to type 'System.String'" , using DataSet as a datasource
Hi All, The following sample code is for testing dw.UpdateData using dataset as the data source. The data retrieval and display part under Form1_Load works fine. However, inputting some values in a new row and calling dw.UpdateData causes the following error: "Unable to cast object of type 'System.DBNull' to type 'System.String'" The error seems to occur when a datawindow column value has been changed from null value. Does anyone know how to fix the error ? Thank you for your advice. I use DW2.5 (build 8542), VS2005 pro, MS SQL Express. ...

"Unable to cast object of type 'System.String' to type 'System.String[]'."
hi i'm using the following statement in my applicationstring[] strTArray = new string[5]; strTArray = (string[])(Session["TextDataArray"]); when i run the application its giving the below error {"Unable to cast object of type 'System.String' to type 'System.String[]'."} can anyone say how to solve this thanks in advance Archu What are you storing in the TextDataArray session? What is the data type you are storing?   RegardsBilal Hadiar, MCP, MCTS, MCPD, MCTMicrosoft MVP - Telerik MVP...

Null values and Profile data "Unable to cast object of type 'System.DBNull' to type 'System.String'"
I've made my own ProfileProvider but when I am trying to read null values by txt.Text = Profile.FirstName I get the error "Unable to cast object of type 'System.DBNull' to type 'System.String'."This is how the code (which I don't write by myself looks like): How to fix the problem??public virtual string FirstName { get { return ((string)(this.GetPropertyValue("FirstName"))); } set { this.SetPropertyValue("FirstName", value); } }  You can check for a null value as sh...

System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'
Hello , I am a data table with null able Columns.I am not able to catch the value for DBNull. I did set a value to be returned as empty in dataset. Here is the code where i am trying to catch.1 public List GetStores() 2 { 3 List tmpStore = new List(); 4 StoresService.shopDBDataSet.StoresDataTable stores = 5 storesService.GetStores(); 6 for (int i = 0; i < stores.Count ; i++) 7 { 8 Store store = new Store(); 9 store.StoreID = stores[i].StoreID...

Unable to cast object of type 'System.DBNull' to type 'System.String'.
Hi i have the following which is meant to check if an image is available and if it isnt it should show a default image however, it gives me this error whenever the image is null in the database. This is the function which returns the error;protected string FormatImageUrl(object url) {if ((url != DBNull.Value) && (url != null) && (url.ToString().Trim().Length > 0)) { //if (File.Exists(url))return (url.ToString().Trim()); } else {return "~/images/default.gif"; } } Hey,Doesn't seem to pass the dbnull check.  Try to do:  if ((!DBNull.Valu...

Unable to cast object of type 'System.DBNull' to type 'System.String'
I have received the following error when I am logged in as administrator.  I wanted to test the load event feature.  Allows me to load and save new event.  I can view event on location view page but when I try to link to "list or calender" view I receive this error "Unable to cast object of type 'System.DBNull' to type 'System.String'.  Debug highlights the <asp:HyperlinkID as errored line. Any assistance would be greatly appreciated Brian   <DayEventTemplate> <div style="padding: 3px;"> <asp:Hyper...

Unable to cast object of type 'System.DBNull' to type 'System.String'.
Hi there, If I add a new event and leave the description field empty the StarterKit seems to throw a big wobbly over the null values in my DB (SQL2000). Have I made a mistake in the installation or something? The problem lies in this line: SharedRoutines.truncate((string)Eval("description")) because description is Null. I want to sort this in this line and I don't want to reply on validators? This is a known issue reported in the Identified Bugs and Fixes for the ClubSite Starter Kit post. I don't think there is one definitive answer. Search on your error message and you'll fin...

Unable to cast object of type 'System.DBNull' to type 'System.String'.
Hi All, I am using Sql server 2005 and VS 2005 C#. Can anybody explain howz solve this prob? Unable to cast object of type 'System.DBNull' to type 'System.String'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.Source Error: Line 3496: get { Line 3497: try { Line 3498: ...

Unable to cast object of type 'System.DBNull' to type 'System.String'.
Hi i get the following error, Unable to cast object of type 'System.DBNull' to type 'System.String'.  A generic image is meant to appear when no image is found in the database for a particular product, this is how the code is laid out;protected string FormatImageUrl(string url) {if (url != null && url.Length > 0) { //if (File.Exists(url))return (url); } else {return "~/Images/CompanyProducts/No_image.jpg"; } }   And the html is like this; <asp:Image ID="Image1" ImageUrl='<%# (string) FormatImageUrl( (string) Ev...

Unable to cast object of type 'System.String' to type 'System.Byte[]' error
Hello, I have some binary data in a MySQL database, and im trying to convert it to a file. Before, when i was using the ms sql express 2005 database, everything was working fine. But then i migrated to MySQL because of budget issues. The following is the block of code that produces the error.private void showDbImage() {string ImageId = Request.QueryString["img"];   //build our query statementstring sqlText = "SELECT DownloadFile, DownloadType FROM DownloadTable WHERE DownloadName = '" + ImageId +"'";  OdbcConnection connection = new OdbcConnection( ConfigurationManager.ConnectionStrings["mySqlConnectionString"].ConnectionString ); OdbcCommand command = new OdbcCommand( sqlText, connection ); //open the database and get a datareader connection.Open();OdbcDataReader dr = command.ExecuteReader(); if (dr.Read()) //yup we found our file {Response.ContentType = dr["DownloadType"].ToString();Response.BinaryWrite((byte[])dr["DownloadFile"]); //downloadFile is the column that contains the binary data } connection.Close(); } However, when this code runs, i get the following error in my browser. Unable to cast object of type 'System.String' to type 'System.Byte[]'. The "DownloadFile" column contains the binary data of the file, and its a "LONGTEXT" type. Before, when i was using sql express 2005, the column was defined as an "image" typ...

ERROR: Unable to cast object of type 'System.Boolean' to type 'System.String'
I created a class to update, insert, select and delete data with an object data source but I am getting the following error... body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-wei...

Unable to cast object of type 'System.DBNull' to type 'System.String'. #2
I am getting this error when I try to run the code below. The error is happening on the last for each loop || foreach (string s in dr.ItemArray) || Please see below:        private void button1_Click(object sender, EventArgs e)        {            string myOutput = "";            DataTable dt = new DataTable();            using (TextReader tr = File.O...

Eventcalender: Unable to cast object of type 'System.DBNull' to type 'System.String'.
 I added an event in the eventcalender. When I try to view the events_calender.aspx I get this error message, what can be wrong??   Server Error in '/bfc_csk' Application. Unable to cast object of type 'System.DBNull' to type 'System.String'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.Source Err...

Unable to cast object of type 'System.DBNull' to type 'System.String'. #2
 Hi:I am totally new to asp.net and downloaded the club website project. I have not done anything to the events page yet but as soon as i tried to add an event I got the following error. "Unable to cast object of type 'System.DBNull' to type 'System.String'." Can someone help me out here?ThanksBrian  This bug has been covered in the Identified Bugs and fixes section.  http://forums.asp.net/t/970081.aspx There are a few solutions and discussions on fixes, you will need to read through it to find the fix. Support@aspsksolutions.com Without kno...

System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Byte[]'.
Hi All, I am trying to retrieve a Picture from an SQL 2005 database. Here is my code:Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim ListingID As String = (Request.QueryString("GUID")) 'Connect to the database and bring back the image contents & MIME type for the specified pictureUsing myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionStringListings").ConnectionString) Const SQL As String = "SELECT [Pic1Ext], [Picture1] FROM [Listings] WHERE [ListingID] = @ListingID"C...

SqlDataSource.Select Error: Unable to cast object of type 'System.Data.DataView' to type 'System.String'.
I am trying to use the select statement to put a field from my database using a SqlDataSource named 'FileBase.' I am using the following code: FileBase.SelectCommand = "SELECT Username FROM Files WHERE Filename = '" & myFileInfo.FullName & "'" myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments()), String)But when I run the code I get the following error:Server Error in '/YorZap' Application. Unable to cast object of type 'System.Data.DataView' to type 'System.String'. Description:...

SqlDataSource.Select Error: Unable to cast object of type 'System.Data.DataView' to type 'System.String'.
I am trying to put the data from a field in my database into a row in a table using the SQLDataSource.Select statement. I am using the following code: FileBase.SelectCommand = "SELECT Username FROM Files WHERE Filename = '" & myFileInfo.FullName & "'" myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments()), String)But when I run the code, I get the following error:Server Error in '/YorZap' Application. Unable to cast object of type 'System.Data.DataView' to type 'System.String'. Descri...

Unable to cast object of type '<>f__AnonymousType1`3[System.Guid,System.String,System.String]' to type 'aspnet_User'.???
Hi everyone, What does this error mean?  ERROR: Unable to cast object of type '<>f__AnonymousType1`3[System.Guid,System.String,System.String]' to type 'aspnet_User'. Thank's a lot /PepePepe JoseNewbie@C#.Net&jRuby What type is in your DataItem?  A Guid? or a String?  Either way, it's telling you cant cast it to a aspnet_User type.  Let us know what your DataItem is and we can help further.Good Luck and happy programming!Let's build community! If my post helped you, mark it as the Answer and I will do the same when you help me.....

Unable to cast object of type 'System.DateTime' to type 'System.String'.
 Hi,      I got this field (dateSubmitted) having a data type of DateTime but I receive this error "Unable to cast object of type 'System.DateTime' to type 'System.String'."       All value for dateSubmitted field are 12/27/2007 12:00:00 AM. cheers,imperialx  imperialx:I got this field (dateSubmitted) having a data type of DateTime but I receive this error "Unable to cast object of type 'System.DateTime' to type 'System.String'." Can you explain it further as to, where you're getting this error ?Thanks,Dhimant Trivedi"When the going gets tough, tough gets going.""Mark as Answer" the post(s) which helped you solve the problem  Hi dhimant,                    I have a Gridview and binded to a LinqDatasource, which shows all data field, one field is named dateSubmitted having a data type NCharVar but an error occurs if I set it to DateTime type. cheers,imperialx       imperialx:one field is named dateSubmitted having a data type NCharVar but an error occurs if I set it to DateTime type. AFAIK, the convert between nvarchar and datetime data type is implicit, which means you don't have to explicitly use cast or convert functions to convert a datetime value to nvarchar or vice versa...

Unable to cast object of type 'System.String' to type 'System.Array'
I really need to get this working! I have dimensioned fnames in line 2 to 200 slots. This code gets all the file names in a subdirectory and places them into an array. First files(), a dynamic array, gets the full path. Then line 9 splits it up into it's parts. I grab the last part (the filename) and store it into fnames. The message is  Unable to cast object of type 'System.String' to type 'System.Array'.  How do I get this to work?  Filenames is an array. Line 9 works. It takes a string (str) and converts it into the Array filenames. Why doesn't the n...

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
I'm getting Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'. anyone knows how to write some code to check if my binary data is null then continue check another data? I've tried but seems that byte and string can't convert...  (hope someone can provide me code in VB and where to insert them :))  Here's my code:Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim ID As Integer = Convert.ToInt32(Request.QueryString("ID"))Using myConnection As New SqlConnection(Configuratio...

Unable to cast object of type 'System.String[]' to type 'System.IConvertible'.
hi expert   i try get the string from request.querystring("CID") from the error messege i know that is string[] (array) how to convert it to int32 and request.querystring("CID") is int value   Line 19: protected void ObjectDataSourceCarPicture_Inserting(object sender, ObjectDataSourceMethodEventArgs e) Line 20: { Line 21: e.InputParameters.Add("CID", Convert.ToInt32(Request.QueryString.GetValues("CID")) ); Line 22: // e.InputParameters.Add("CID", Convert.ToInt32( Convert.ToString( a Request.QueryString.GetValues("CID"))))); Line 23: } i already try search from google but still not get the solution Why dont you carry it out this way: string result = Request.QueryString["CID"]; //Parses the given string, throwing some kind of error when its //not a number int cid = Int32.Parse(result);And then use the cid whereever you want!Hope that helps.So simple... yet so effective.My "Life"ly Blog thanks for reply it works other that i did a mistake Request.QueryString.GetValues("CID")   to Request.QueryString.Get("CID") Watch out for the other thing that I mentioned in my code.. you can use Request.QueryString["CID"] to index into the QueryString collection. Saves some hassle.Smiles.So simple... yet so effective.My "Life"ly Blog...

Unable to cast object of type 'System.Int64' to type 'System.String'
Hi friends I am getting the following error..."Unable to cast object of type 'System.Int64' to type 'System.String'." for the following line of code  if ((QSDealID) == (dr.GetString(1).ToString()))...............need ur help...Gurjeet,England First of all, the ToString of the GetString method is not needed because the GetString will return a string. The prolem with your code is that QSDealID is of type System.Int64, right? So a Int64 can't be compared with a string. The DataReader have a method that can return a Int64, so instead of using GetString(1), use GetInt64. if (QSDealID == dr.GetInt64(1))/Fredrik Normén - fredrikn @ twitterMicrosoft MVP, MCSD, MCAD, MCTASPInsidersMy Blog is ur QSDealID is interger??? i think if it is then u r required to convert it into string or convert dr.Getstring(0).tostring into Int64Thanks, Mahadeo-----------------------------------------------Best is Not the END point, but a starting point for Innovation------------------------------------------------Remember to mark posts as the "Answer" to help future users....

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
Hi, I have developed a custom server control for .NET Framework 2.0. The server control has a property named BinaryData of type byte[]. I marked this property to be data bindable. Now, I have varbinary(Max) type of field in my SQL Database and I have used SQLDataSource and bound this varbinary(Max) field with the property BinaryData (byte[]) of my control. It is working fine as long as the data value is not NULL. Now, In my control, I have handled the NULL value so that no Exception is thrown. Still, when I bind this property using the SQLDataSource, I get Error "Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'." I am not sure if I can do anything to stop this erro within my control. If it is not possible from the control, then what is the workaround that I can do in my ASPX page in order to stop this error ? Thanks a lot in advance. You are reading in these values from a reader and casting them to their appropriate values. However, since you allow null values in your database table, if there is a null value in your resultant set, it will return DBNull.Value to your reader. This value cannot be casted into a primitive type. Thus you must check for it when you are reading it in and assign it accordingly. For instance,this._strSomeValue = (sdrReader["SomeField"] == DBNull.Value)? "assign default value" : sdrReader["SomeField"].ToString();basically check if it is DBNull.Value when you are reading...

Web resources about - How do I get around this error "Unable to cast object of type 'System.DBNull' to type 'System.String' " - asp.net.getting-started

Resources last updated: 3/8/2016 3:00:05 AM