Error showing up: Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'.

Hi,

I am trying to pass date values from two textboxes in a stored procedure from ASP.net page. However, it seems it is not passing the date properly.

I am getting the following error at the following line:

cmd_r.Parameters("@initial_est_date").Value = Convert.ToDateTime(Textbox1)

 and the error is as stated in the title.

I would appreciate any help to resolve this. Thanks

 CODE:

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<%@ Import Namespace="System.Data.Common" %>

<%@ Import Namespace="System.IO" %>

<%@ Import Namespace="System.Text" %>

 

<script language="VB" runat="server">

 

Sub Page_Load(ByVal Source As Object, ByVal E As EventArgs)

If Not Page.IsPostBack Then

Dim oConn As SQLConnection

Dim oComm As SQLCommand

Dim oReader As SQLDataReader

Dim sSQL As String

Dim sConn As String

sSQL = "SELECT familycode + ', ' + Description + ', ' + materialtype As familycode from tblFamilyCode "

sConn = "server=USILDEK1-21001\AVIS;database=pubs;Trusted_Connection=yes"

oConn = New SQLConnection(sConn)

oConn.Open()

oComm =
New SQLCommand(sSQL, oConn)

oReader = oComm.ExecuteReader()

MySelect.DataSource() = oReader

MySelect.DataBind()

End If

End Sub

 

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)

 

Dim dr As SqlDataReader

Dim i As Integer

Dim strLine, filePath, fileName, fileExcel, link As String

Dim objFileStream As FileStream

Dim objStreamWriter As StreamWriter

Dim nRandom As Random = New Random(DateTime.Now.Millisecond)

Dim fs As Object, myFile As Object

 

Dim conn_r As New SqlConnection( _

"server=USILDEK1-21001\avis;database=pubs;Integrated Security=SSPI")

 

Dim cmd_r As New SqlCommand("test_familycode_daterange", conn_r)

cmd_r.CommandType = CommandType.StoredProcedure

'Add the familycode parameter

cmd_r.Parameters.Add("@familycode", SqlDbType.VarChar, 50)

cmd_r.Parameters("@familycode").Value = Left((Convert.ToString(MySelect.SelectedItem)), 4)

'Add the lower date parameter

cmd_r.Parameters.Add("@initial_est_date", SqlDbType.DateTime, 20)

cmd_r.Parameters("@initial_est_date").Value = Convert.ToDateTime(Textbox1)

'Add the upper date parameter

cmd_r.Parameters.Add("@final_est_date", SqlDbType.DateTime, 20)cmd_r.Parameters("@final_est_date").Value = Convert.ToDateTime(Textbox2)

 

 

'Create a excel file with timestamp

fileExcel = "FamilyCode_" & DateTime.Now.ToShortDateString().Replace("/", "").Replace(" ", "") & "_" & DateTime.Now.ToLongTimeString().Replace(":", "").Replace(" ", "") & ".xls"

'Set a virtual folder to save the file.

 

filePath = Server.MapPath(
"~")

fileName = filePath & "\" & fileExcel

'Use FileStream to create the .xls file.

objFileStream = New FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write)objStreamWriter = New StreamWriter(objFileStream)

conn_r.Open()

dr = cmd_r.ExecuteReader()

'Enumerate the field names and records that are used to build the file.

For i = 0 To dr.FieldCount - 1

strLine = strLine & dr.GetName(i).ToString & Chr(9)

Next

'Write the field name information to file.

objStreamWriter.WriteLine(strLine)

'Reinitialize the string for data.

strLine = ""

'Enumerate the database that is used to populate the file.

While dr.Read()For i = 0 To dr.FieldCount - 1

strLine = strLine & dr.GetValue(i) & Chr(9)

Next

objStreamWriter.WriteLine(strLine)

strLine = ""

End While

'Clean up.

dr.Close()

conn_r.Close()

objStreamWriter.Close()

objFileStream.Close()

End Sub

</script>

<html>

<body style="font: 10pt verdana">

<form id="Form1" runat="server">

<h3><font face="Verdana">Parameterized Select to export date from Stored Procedure</font></h3>

Select a Family Code:

<asp:DropDownList ID="MySelect" DataTextField="familycode" DataValueField="familycode" Runat="server" />

<br />

<br />

Select Initial Estimate Date:

<asp:textbox id="Textbox1" runat="server" text=""/>

<br />

<br />

Select Final Estimate Date:

<asp:textbox id="Textbox2" runat="server" text=""/>

<br />

<br />

<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button" />

</form>

</body>

</html>

Stored Procedure Code:

CREATE PROCEDURE test_familycode_daterange
@familycode varchar(50),
@initial_est_date datetime,
@final_est_date datetime

As
select * from temp_estimate
where familycode = @familycode
AND estimatetime >= @initial_est_date
AND estimatetime < @final_est_date
order by FullEstimateNo
GO

0
gamaz
8/4/2008 1:01:55 AM
asp.net.web-forms 93655 articles. 6 followers. Follow

2 Replies
2176 Views

Similar Articles

[PageSpeed] 39

 

Hi ,

 

    You are trying to convert textbox object to date not the value of a text box. Replace all “Textbox1” with “Textbox1.Text

 

    Textbox1.Text gives the value of the textbox.

           

Happy Coding

 

Please mark as “Answer” if you find this post helpful

 

0
pnv
8/4/2008 2:16:07 AM

Thanks Ravikiran for your help. It worked perfect and my errors are taken care of.

Regards.

0
gamaz
8/4/2008 3:28:51 AM
Reply:

Similar Artilces:

Unable to cast object of type 'System.Web.UI.WebControls.Label' to type 'System.Web.UI.WebControls.TextBox'
I am attempting to "Update" a field in a Datagrid, but no matter what I do (Using either Label or Text Boxes)  I keep getting the same error: Unable to cast object of type 'System.Web.UI.WebControls.Label' to type 'System.Web.UI.WebControls.TextBox' The Error is highlighted below in the Sub... <==THE FIELD THAT CALLS THE ERROR  Any help would be greatly appreciated !!! Thanks !!   The code is as follows... <table border=0 height=210 bordercolor=olive ><tr valign=top><td> <asp:datagrid id="FacilityDataGrid"...

Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'
Hello, Goal: enter a number in two fields HoursPerUnit and PeoplePerUnit and the value for the third field, TotalHoursPerUnit will populate after the the number in the two fields have been caculated.  Using the code below I receive the error message above.  Please tell me what am I doing wrong? Do I need to cast the text as a literal?  Please help? Thank you in advance, <%@ Page Language="VB" MasterPageFile="Default.master" AutoEventWireup="false" CodeFile="frmHR.aspx.vb" Inherits="frmHR"...

Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'.
Hi, any idea why I'm getting the following error?Line 45: protected void CartGrid_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e) Line 46: { Line 47: TextBox QuantityTextBox = (TextBox)CartGrid.Rows[e.RowIndex].Cells[2].Controls[0]; Line 48: int Quantity = Convert.ToInt32(QuantityTextBox.Text); Line 49: Are you sure that the control at CartGrid.Rows[e.RowIndex].Cells[2].Controls[0] isn't a LiteralControl?  How are you creating code this in your code?Brent JenkinsASP.NET, C#, Web Developerwww.valewebdesign.co.uk  ...

Unable to cast object of type 'System.Web.UI.WebControls.FormView' to type 'System.Web.UI.WebControls.DropDownList'.
Hi,  I have a formview with a dropdownlist created dynamically. i want to determine whether the dropdownlist was clicked. the code is written in the FormView1_DataBound method. I get the following error in the line below that is in italics and underlined: Unable to cast object of type 'System.Web.UI.WebControls.FormView' to type 'System.Web.UI.WebControls.DropDownList'.   Here is my code: ddl_iFullname = New DropDownList ddl_iFullname.ID = "ddl_iFullname" ddl_iFullname.DataSource = ObjectDataSource3 ddl_iFullname.DataTextField = "fullname" ddl_iFullname.DataValueField = "...

Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.Parameter'.
I'm getting this error on a vb.net page the needs to execute two separate stored procedures.  The first one, is the main insert, and returns the identity value for the ClientID.  The second stored procedure inserts data, but needs to insert the ClientID returned in the first stored procedure.  What am I doing wrong with including the identity value "ClientID" in the second stored procedure?  Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.Parameter'. Description: An unhandled exception occurred during t...

Unable to cast object of type 'System.Int32' to type 'System.Web.UI.WebControls.DataKey'
hi , i have a datalist with an itemtemplate section that contains an image and a delete button to delete the corresponding image . <asp:DataList ID="DataList1" CellSpacing="25" runat="server" DataSourceID="sqldatasource3" DataKeyField="ID" repeatColumns="4" repeatdirection="Horizontal" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="0px" CellPadding="3" > <ItemTemplate> <table border="0" cellpadding="0" cellspacing="0" > <tr> <a href='<%# DataBinder.Eval(Container.DataItem, "image", "ImageViewer.aspx?id={0}") %>' > <img a...

Unable to cast object of type 'System.EventArgs' to type 'System.Web.UI.WebControls.GridViewRowEventArgs'
hi this is really really bugging me please help. I have a web appliction that uses a Master Page. On one of the content pages I am presenting a gridview control bound to a spreadsheet. The gridview is contained within an ajax update panel. I want to add attributes to the rows of the gridview control once databound (mouseover effect). However I am getting the following error:- Unable to cast object of type 'System.EventArgs' to type 'System.Web.UI.WebControls.GridViewRowEventArgs' Can anyone help please. Here is the aspx code:-  <%@ Page Language="v...

Unable to cast object of type 'System.Web.Configuration.ScriptingScriptResourceHandlerSection' to type 'System.Web.Configuration.ScriptingScriptResourceHandlerSection'.
Hello, I get this lovely error whenever I attempt to load an AJAXToolKit ScriptManager. It is the only one I have on the page. If I use the regulare script manager, my extenders don't detect it. I'm placing the ScriptManager just after the <Form> tag. The frustrating part is that it works when I preview it in the browser from my development machine it works, but once I place it the live server, it crashes on me . I've installed all of the .dlls in the proper places. Also, I'm trying to attempt to do this when creating a new site with the AJAX ToolKit enabled templat...

Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Compilation.BuildResultCompiledGlobalAsaxType'
I always get the below exception if I make a configuration change to the web.config file then request a page without re-building the project. Exception: Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Compilation.BuildResultCompiledGlobalAsaxType'. Stack Trace: [InvalidCastException]: Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Compilation.BuildResultCompiledGlobalAsaxType'.   at System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean isPrec...

Unable to cast object of type 'System.Web.Configuration.ScriptingScriptResourceHandlerSection' to type 'System.Web.Configuration.ScriptingScriptResourceHandlerSection'.
Hello, I get this lovely error whenever I attempt to load an AJAXToolKit ScriptManager. It is the only one I have on the page. If I use the regulare script manager, my extenders don't detect it. I'm placing the ScriptManager just after the <Form> tag. The frustrating part is that it works when I preview it in the browser from my development machine it works, but once I place it the live server, it crashes on me . I've installed all of the .dlls in the proper places. Also, I'm trying to attempt to do this when creating a new site with the AJAX ToolKit enabled templat...

Unable to cast object of type 'System.Web.Configuration.ScriptingAuthenticationServiceSection' to type 'System.Web.Configuration.ScriptingAuthenticationServiceSection'.
I have tried to upgrade an existing application from VS2005 to VS2008.  I downloaded the latest AjaxControlToolkit and referenced it in my project.  I'm getting the below error when I try to deploy to our QA servers.  I'm NOT seeing the issue on our local development machines that have VS2008 installed.   Unable to cast object of type 'System.Web.Configuration.ScriptingAuthenticationServiceSection' to type 'System.Web.Configuration.ScriptingAuthenticationServiceSection'.  What piece am I missing in the deployment?  All the w...

Error Serializing Value 'System.Web.UI.WebCOntrols.TreeNode' of type 'System.Web.UI.WebCOntrols.TreeNode'
Hi, I am  getting the error stated in the subject when i am storing a TreeNode in a ViewState and then using it as follows if (ViewState["ProductCounty"]!=null) { TreeNode _productCountyNode = DataTree.FindNode(((TreeNode)ViewState["ProductCounty"]).ValuePath); _productCountyNode.Expand(); } what could be causing this error? Hi, I believe TreeNode isn't serializable in a way its required for objects which can be put to ViewState - as reference - (TreeNode implements IStateManager and is meant to work together with TreeView itself saving it...

Unable to cast object of type 'System.Web.UI.WebControls.ContentPlaceHolder' to type 'CustomerDB._Default'.
If have  a problem regarding the error message: Unable to cast object of type 'System.Web.UI.WebControls.ContentPlaceHolder' to type 'CustomerDB._Default'. I am using MaterPages with two ContentPlaceHolders in my default.aspx In the fist ContentPlaceHolder I have added a ordinary placeholder where I loads a Usercontrol. So far so good.The usercontrols search for customers and creates a gridview with a link that  the user can click on. When the user clicks it runs a class (located in default.aspx) that should present data in the second ContentPlaceholder, ...

Help Required
Server Error in '/' Application.--------------------------------------------------------------------------------Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Util.ITypedWebObjectFactory'. [InvalidCastException: Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Util.ITypedWebObjectFactory'.] System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +123 System.Web.Compilation.BuildMa...

Web resources about - Error showing up: Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'. - asp.net.web-forms

Resources last updated: 1/8/2016 9:24:29 AM