Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server






SuperbHosting.net & Arvixe.com have generously sponsored dedicated servers and web hosting to ensure a reliable and scalable dedicated hosting solution for BigResource.com.







Unable To Cast COM Object Of Type 'System.__ComObject' To Class Type 'System.Data.SqlClient.SqlConn


Dear all,
 
I am stuck with a SSIS package and I can€™t work out. Let me know what steps are the correct in order to solve this.
At first I have just a Flat File Source and then Script Component, nothing else.
 
Error:
 
 



[Script Component [516]] Error: System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.    at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.HandleUserException(Exception e)    at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.AcquireConnections(Object transaction)    at Microsoft.SqlServer.Dts.Pipeline.ManagedComponentHost.HostAcquireConnections(IDTSManagedComponentWrapper90 wrapper, Object transaction)
 
 
 
Script Code (from Script Component):
 
 
 
' Microsoft SQL Server Integration Services user script component
' This is your new script component in Microsoft Visual Basic .NET
' ScriptMain is the entrypoint class for script components
 
Imports System
Imports System.Data.SqlClient
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
 
 
Public Class ScriptMain
    Inherits UserComponent
 
 
    Dim nDTS As IDTSConnectionManager90
    Dim sqlConnecta As SqlConnection
    Dim sqlComm As SqlCommand
    Dim sqlParam As SqlParameter
 
 
    Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
 
        Dim valorColumna As String
        Dim valorColumna10 As Double
 
 
        valorColumna = Row.Column9.Substring(1, 1)
 
        If valorColumna = "N" Then
            valorColumna10 = -1 * CDbl(Row.Column10 / 100)
        Else
            valorColumna10 = CDbl(Row.Column10 / 100)
        End If
 
        Me.Output0Buffer.PORCRETEN = CDbl(Row.Column11 / 100)
        Me.Output0Buffer.IMPRETEN = CDbl(Row.Column12 / 100)
        Me.Output0Buffer.EJERCICIO = CInt(Row.Column2)
        Me.Output0Buffer.CODPROV = CInt(Row.Column7)
        Me.Output0Buffer.MODALIDAD = CInt(Row.Column8)
        Me.Output0Buffer.NIFPERC = CStr(Row.Column3)
        Me.Output0Buffer.NIFREP = CStr(Row.Column4)
        Me.Output0Buffer.NOMBRE = CStr(Row.Column6)
        Me.Output0Buffer.EJERDEV = CDbl(Row.Column13)
 
        With sqlComm
            .Parameters("@Ejercicio").Value = CInt(Row.Column2)
            .Parameters("@NIFPerc").Value = CStr(Row.Column3)
            .Parameters("@NIFReP").Value = CStr(Row.Column4)
            .Parameters("@Nombre").Value = CStr(Row.Column6)
            .Parameters("@CodProv").Value = CInt(Row.Column7)
            .Parameters("@Modalidad").Value = CInt(Row.Column8)
            .Parameters("@ImpBase").Value = valorColumna10
            .Parameters("@PorcReten").Value = CDbl(Row.Column11 / 100)
            .Parameters("@ImpReten").Value = CDbl(Row.Column12 / 100)
            .Parameters("@EjerDev").Value = CDbl(Row.Column13)
 
            .ExecuteNonQuery()
        End With
 
 
    End Sub
    Public Overrides Sub AcquireConnections(ByVal Transaction As Object)
 
        Dim nDTS As IDTSConnectionManager90 = Me.Connections.TablaMODELO80
        sqlConnecta = CType(nDTS.AcquireConnection(Nothing), SqlConnection)
 
    End Sub
    Public Overrides Sub PreExecute()
 
        sqlComm = New SqlCommand("INSERT INTO hac_modelo180(Ejercicio,NIFPerc,NIFReP,Nombre,CodProv,Modalidad,ImpBase,PorcReten,ImpReten,EjerDev) " & _
    "VALUES(@Ejercicio,@NIFPerc,@NIFReP,@Nombre,@CodProv,@Modalidad,@ImpBase,@PorcReten,@ImpReten,@EjerDev)", sqlConnecta)
        sqlParam = New SqlParameter("@Ejercicio", Data.SqlDbType.SmallInt)
        sqlComm.parameters.add(sqlParam)
        sqlParam = New SqlParameter("@NIFPerc", Data.SqlDbType.Char)
        sqlComm.parameters.add(sqlParam)
        sqlParam = New SqlParameter("@NIFReP", Data.SqlDbType.Char)
        sqlComm.parameters.add(sqlParam)
        sqlParam = New SqlParameter("@Nombre", Data.SqlDbType.VarChar)
        sqlComm.parameters.add(sqlParam)
        sqlParam = New SqlParameter("@CodProv", Data.SqlDbType.TinyInt)
        sqlComm.parameters.add(sqlParam)
        sqlParam = New SqlParameter("@Modalidad", Data.SqlDbType.SmallInt)
        sqlComm.parameters.add(sqlParam)
        sqlParam = New SqlParameter("@ImpBase", Data.SqlDbType.Decimal)
        sqlComm.parameters.add(sqlParam)
        sqlParam = New SqlParameter("@PorcReten", Data.SqlDbType.Decimal)
        sqlComm.parameters.add(sqlParam)
        sqlParam = New SqlParameter("@ImpReten", Data.SqlDbType.Decimal)
        sqlComm.parameters.add(sqlParam)
        sqlParam = New SqlParameter("@EjerDev", Data.SqlDbType.Decimal)
        sqlComm.Parameters.Add(sqlParam)
 
    End Sub
 
 
    Public Sub New()
 
    End Sub
    Public Overrides Sub ReleaseConnections()
        nDts.ReleaseConnection(sqlConnecta)
    End Sub
 
    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub
End Class
 
 
 
 
 
 
 
Thanks a lot for your help  
 
 
 


View Complete Forum Thread with Replies
Sponsored Links:

Related Messages:
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'. 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.Data.DataView' to type 'System.String'.Source Error: Line 54: FileBase.SelectCommand = "SELECT Username FROM Files WHERE Filename = '" & myFileInfo.FullName & "'"
Line 55: 'myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments).GetEnumerator.Current, String)
Line 56: myDataRow("Username") = CType(FileBase.Select(New DataSourceSelectArguments()), String)
Line 57:
Line 58: filesTable.Rows.Add(myDataRow)Source File: D:YorZapdir_list_sort.aspx    Line: 56 Stack Trace: [InvalidCastException: Unable to cast object of type 'System.Data.DataView' to type 'System.String'.]
ASP.dir_list_sort_aspx.BindFileDataToGrid(String strSortField) in D:YorZapdir_list_sort.aspx:56
ASP.dir_list_sort_aspx.Page_Load(Object sender, EventArgs e) in D:YorZapdir_list_sort.aspx:7
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +13
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +45
System.Web.UI.Control.OnLoad(EventArgs e) +80
System.Web.UI.Control.LoadRecursive() +49
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3743
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210 Please help me!

View Replies !   View Related
@PARAM1 : Unable To Cast Object Of Type 'System.Data.SqlTypes.SqlInt32 To Type System.IConvertable
I get the following message in the vs2005 querybuilder when i do a preview:

 

***********************************
SQL Execution Error.

Executed SQL statement: SELECT Schoolindex, Variant, VVSchool, [index], indincl, VVRuimtes, School FROM School WHERE (Schoolindex = @PARAM1)

 

Error Source: SQL Server Compact Edition ADO.NET Data Provider


Error Message: @PARAM1 : Unable to cast object of type 'System.Data.SqlTypes.SqlInt32 to type System.IConvertable'.
****************************************

The same querypreview works fine without the parameter:

 

SELECT Schoolindex, Variant, VVSchool, [index], indincl, VVRuimtes, School FROM School WHERE (Schoolindex = 186)

 

Can anybody tell me why this is?
And tell me a way to get the tableadapter working?

 

Anne-Jan Tuinstra

View Replies !   View Related
Unable To Cast Object Of Type 'System.Object' To Type 'System.Data.DataSet'.
 

hi  i dont know how to do type casting.

this.Variables.ObjVariable this objVariables i have create in variable place below like this

 

Name:Variable datatype int32 values 0

Name: NumberofRowsdatatype int32  values 10000

Name: ObjVariable  datatype Object

 

My code

 

 

public override void CreateNewOutputRows()

{

/*

Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".

For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".

*/

System.Data.OleDb.OleDbDataAdapter oLead = new System.Data.OleDb.OleDbDataAdapter();

//System.Data.Odbc.OdbcDataAdapter oLead = new System.Data.Odbc.OdbcDataAdapter();

//SqlDataAdapter oLead = new SqlDataAdapter();

System.Data.DataTable dt = new System.Data.DataTable();

DataSet ds = (DataSet)this.Variables.ObjVariable;  // here i am getting error

ds.Tables.Add(dt);


ADODB.Record rs = new ADODB.Record();

 

oLead.Fill(ds, rs, "Variables");

foreach (DataRow row in dt.Rows)

{

{

Output0Buffer.AddRow();

Output0Buffer.Column = (int)row["Column"];

Output0Buffer.Column1 = row["Column1"].ToString();

Output0Buffer.Column2 = row["Column2"].ToString();

}

}


}

}

This is the error

Unable to cast object of type 'System.Object' to type 'System.Data.DataSet'.

at ScriptMain.CreateNewOutputRows()

at UserComponent.PrimeOutput(Int32 Outputs, Int32[] OutputIDs, PipelineBuffer[] Buffers)

at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.PrimeOutput(Int32 outputs, Int32[] outputIDs, PipelineBuffer[] buffers)

 

thanks

kedaranth

View Replies !   View Related
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 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.String' to type 'System.Web.UI.WebControls.Parameter'.Source Error:




Line 14: If li.Selected Then
Line 15: InsertClientCompanyType.InsertParameters("CompanyTypeID").DefaultValue = li.Value
Line 16: InsertClientCompanyType.InsertParameters("ClientID") = ViewState("ClientID")
Line 17:
Line 18:
Source File: C:InetpubwwwrootIntranetExternalAppsNewEmploymentClientNewClient.aspx.vb    Line: 16
Here is my code behind... What am I doing wrong with grabbing the ClientID from the first stored procedure insert? 
 
Protected Sub InsertNewClient_Inserted(ByVal sender As Object, ByVal e As SqlDataSourceStatusEventArgs)ClientID.Text = e.Command.Parameters("@ClientID").Value.ToString()ViewState("ClientID") = e.Command.Parameters("@ClientID").Value.ToString()End SubProtected Sub Submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Submit.ClickInsertNewClient.Insert()For Each li As ListItem In CompanyTypeID.Items
If li.Selected ThenInsertClientCompanyType.InsertParameters("CompanyTypeID").DefaultValue = li.ValueInsertClientCompanyType.InsertParameters("ClientID") = ViewState("ClientID")InsertClientCompanyType.Insert()End IfNextEnd Sub

View Replies !   View Related
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 

View Replies !   View Related
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.

View Replies !   View Related
Unable To Cast Object Of Type 'System.Xml.XmlTextReaderImpl'
I'm getting the following error:  Unable to cast object of type 'System.Xml.XmlTextReaderImpl' to type 'System.Xml.XmlTextReader'. This works in .net 1.1 but having issues in the conversion to 2.0.
Public Function RunSPReturnXMLReader(ByVal strSP As String, ByVal ParamArray params() As SqlParameter) As System.Xml.XmlTextReader
Dim objHelperConnection As SqlConnectionobjHelperConnection = New SqlConnection(sConnect)Dim myXmlReader As System.Xml.XmlReader = objHelperCommand.ExecuteXmlReader()
RunSPReturnXMLReader = myXmlReader - GETTING ERROR HERE
End Function
 
Thanks...

View Replies !   View Related
Unable To Cast Object Of Type 'System.Char'
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections;

public partial class UserDefinedFunctions
{  
        [Microsoft.SqlServer.Server.SqlFunction(FillRowMethodName="Obj_Row",
                                                IsDeterministic=true,
                                                IsPrecise=true,
                                                TableDefinition = "ObjID int,ObjCategoryID int,ObjValue nvarchar(400)",
                                                DataAccess= DataAccessKind.Read)]

        public static IEnumerable Obj_IDs(SqlInt32 Data_1, SqlInt32 Data_2, SqlInt32 Data_3)
        {
                using (SqlConnection conn = new SqlConnection("context connection=true"))
                {
                    try
                    {
                        string sql;
                        switch(Data_1.Value)
                        {
                            case 1:
                             sql= @"Select Obj_ID, Obj_Categoy_ID, Obj_Value
                                    from (select ObjA_ID as Obj_ID, Obj_Category_ID, Obj_Value from dbo.function_A(12,23))A,
                                         (select ObjA_ID as Obj_ID, Obj_Category_ID, Obj_Value from dbo.function_A(15,27))B
                                    Where A.ObjA_ID= B.ObjA_ID
                                        and Obj_ID in (Select ObjB_ID from tbl_Object where Obj_CategoryID=10)";
                                break;
                            default:
                                sql = @"Select Obj_ID, Obj_Categoy_ID, Obj_Value from tbl_Object";
                                break;
                        }

                            SqlCommand cmd = new SqlCommand(sql, conn);
                            SqlDataAdapter da = new SqlDataAdapter(cmd);
                            DataTable dt = new DataTable();
                            da.Fill(dt);
                            conn.Open();
                            return dt.Rows;
                    }
                    catch (Exception ex)
                    {
                        ex.Message.ToString();
                        return "";
                    }
                    finally
                    {
                        conn.Close();
                    }

                }

        }
        public static void Obj_Row(Object item, out int ObjID, out int ObjCategoryID, out string ObjValue)
        {
            DataRow row = (DataRow)item;
            ObjID = Convert.ToInt32(row["Obj_ID"]);
            ObjCategoryID = Convert.ToInt32(row["Obj_Categoy_ID"]);
            ObjValue = row["Obj_Value"].ToString();
        }

};
=================

compile with no error. Call funtion from sql studio the error come ==>

Msg 6260, Level 16, State 1, Line 1
An error occurred while getting new row from user defined Table Valued Function :
System.InvalidCastException: Unable to cast object of type 'System.Char' to type 'System.Data.DataRow'.
System.InvalidCastException:
   at UserDefinedFunctions.Object_Row(Object item, Int32& ObjID, Int32& ObjCategoryID, String& ObjValue)
.
when I change SQL script to simple not "nested select" it work fine. How to get out of this kind of trouble????!!!!

View Replies !   View Related
Unable To Cast Object Of Type 'System.String' Error Help
Unable to cast object of type 'System.String' to type 'System.Web.UI.DataSourceSelectArguments'.
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.String' to type 'System.Web.UI.DataSourceSelectArguments'. 
Hi, In my pageload i have data retriving from a page and i want it to load it in the GridView. i have GridView and SqlDataSource but when the page loads i am getting the above error. i am not sure what im doing wrong here. i tried different ways. but no luck Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Thenfp = CType(Context.Handler, Member)
'lblEmail.Text = fp.EMM.ToString
'this labelbox for Email address is under the Name'lblEmail.Text = fp.EmailAddress.ToString
 
 Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("imacstestConnectionString").ConnectionString)
Dim cmd As SqlCommand = New SqlCommand("SELECT , [fname], [mname], [lname], [address], [city], [state], [zip], [phone] FROM [t_CustomerAcct] WHERE = @email", conn)cmd.Parameters.AddWithValue("@email", fp.EMM.ToString)
conn.Open()
SqlDataSource1.Select(cmd.ExecuteScalar())
'.ExecuteScalar()
 
conn.Close()
End If
End Sub

View Replies !   View Related
System.Security.SecurityException: Request For The Permission Of Type 'System.Data.SqlClient.SqlClientPermission, System.Data
I have created a windows library control that accesses a local sql database

I tried the following strings for connecting

Dim connectionString As String = "Data Source=localhostSQLEXPRESS;Initial Catalog=TimeSheet;Trusted_Connection = true"

Dim connectionString As String = "Data Source=localhostSQLEXPRESS;Initial Catalog=TimeSheet;Integrated Security=SSPI"

 

I am not running the webpage in a virtual directory but in

C:Inetpubwwwrootusercontrol

and I have a simple index.html that tries to read from an sql db but throws

the error

System.Security.SecurityException: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
   at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
   at System.Security.PermissionSet.Demand()
   at System.Data.Common.DbConnectionOptions.DemandPermission()
   at System.Data.SqlClient.SqlConnection.PermissionDemand()
   at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection,

etc etc

 The action that failed was:
Demand
The type of the first permission that failed was:
System.Data.SqlClient.SqlClientPermission
The Zone of the assembly that failed was:
Trusted


I looked into the .net config utility but it says unrestricted and I tried adding it to the trusted internet zones in ie options security

I think that a windows form connecting to a sql database running in a webpage should be simple

to configure what am I missing?

View Replies !   View Related
Request For The Permission Of Type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, Pu
 
I created a .net console application within which I connect to a sql server (not local) as follows,

 
string conn_str = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=QuantEquitySql;Data Source=server name";

SqlConnection conn = new SqlConnection(conn_str);

conn.Open();
.
Everything works fine when I run it from my computer. When I try to run it from a network share I get the following error,
 
Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
 
I am using Visual Studio 2005 and .Net framwork v2.0.50727.
 
Does anybody know a fix to this problem?
 
Thanks
 

View Replies !   View Related
A First Chance Exception Of Type 'System.Data.SqlClient.SqlException' Occurred In System.data.dll
Hi,
I've written this code multiple times now. But for the first time i get an error at the line underlined. My procedure runs perfectly when i execute it through Sql Query analyzer.
plzz help.. Its urgent and am unable to find the reason for this error "A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in system.data.dll"
Thanks !SqlConnection conn = new SqlConnection(DbConnectionString);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "dbo.rqryTradesPRR";
cmd.Parameters.Add("@COBDate",SqlDbType.DateTime).Value = "2002-10-31 00:00:00.000" ;
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// have written something here

}
 Thanks in advance !
 

View Replies !   View Related
System.Data.SqlClient.SqlException: The Conversion Of A Char Data Type To A Datetime Data Type Resulted In An Out-of-range Datetime Value.
After testing out the application i write on the local pc. I deploy it to the webserver to test it out. I get this error.

System.Data.SqlClient.SqlException: The conversion of a char data type to a
datetime data type resulted in an out-of-range datetime value.

Notes: all pages that have this error either has a repeater or datagrid which load data when page loading.

At first I thought the problem is with the date, but then I can see
that some other pages that has datagrid ( that has a date field) work
just fine.

anyone having this problem before?? hopefully you guys can help.

Thanks,

View Replies !   View Related
The Type 'System.Data.SqlClient.SqlDataReader' Has No Constructors Defined
I am trying to bind the data to a list box....i am using a stored procedure instead of a select query. Unfortunately the error is throwing up. Correct me where iam going wrong. Is my syntax correct 
 SqlConnection cn = new SqlConnection("User id=******;password=******;database=sampleecsphase2test;Data source=primasqltst\qa");
cn.Open();SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;SqlDataReader dr = new SqlDataReader();
dr = cmd.ExecuteReader();
listBox1.DataSource = dr;

View Replies !   View Related
The Type 'System.Data.SqlClient.SqlDataReader' Has No Constructors Defined
Dear all, I'm using sqldatareader to return data that i need and then bind it to the gridview. Anyway, I'm facing the above error message. Please help, thanks.  Levine

View Replies !   View Related
Cannot Implicitly Convert Type 'System.Data.SqlClient.SqlDataReader' To 'int'
Hi,
 
I sometimes get these error messages. Does this sound familiar? Does anyone know what I am doing wrong?
 

Cannot implicitly convert type 'System.Data.SqlClient.SqlDataReader' to 'int'  (SQL-server)
 
Cannot implicitly convert type 'int' to 'System.Data.OleDb.OleDbDataReader'  (Access DB)
 
TIA

View Replies !   View Related
BC30311: Value Of Type 'System.Data.SqlClient.SqlDataReader' Cannot Be Converted To 'String'.
Does anyone know what the problem is?


Sub Page_Init(sender As Object, e As EventArgs)
Dim txtName As New TextBox()
Dim txtPart As New TextBox()
Dim txtEach As New TextBox()
Dim txtTotal1 As New TextBox()
Dim txtSubtotal As New TextBox()
Dim txtTax As New TextBox()
Dim txtShipping As New TextBox()
Dim txtTotal2 As New TextBox()

Dim prod_id As Integer
Dim id As Integer
id = Request.Querystring("prod_id")
txtName.Text = GetName(id).................this is the problem line

phName.Controls.Add(txtName)
phPart.Controls.Add(txtPart)
phEach.Controls.Add(txtEach)
phTotal1.Controls.Add(txtTotal1)
phSubtotal.Controls.Add(txtSubtotal)
phTax.Controls.Add(txtTax)
phShipping.Controls.Add(txtShipping)
phTotal2.Controls.Add(txtTotal2)

End Sub


I'm trying to populate dynamically rendered textbox's, how should I do that too?

View Replies !   View Related
Request For The Permission Of Type 'System.Data.SqlClient.SqlClientPermission' Failed In MOSS 2007
 

Hi,
 
I have created a web part in ASP.Net. this web part is extracting data from the sql server database and displaying it on the web part page.
This web part is working fine with asp.net application, but when i deploy it with MOSS. it is reaising security exception error like.
 
Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
 
I have made the entry under the safe control list of web.config file. but still i am getting error any suggestion wud be highly appreciable..
 
pls reply me on sanjiv.singh@kpitcummins.com.
 
thanks you so much.
 
Regards,
Sanjiv Singh

View Replies !   View Related
Request For The Permission Of Type 'System.Data.SqlClient.SqlClientPermission' Failed - Server Report
I am using embedded code in a server report to access information from a SQL database.  The report runs fine on my development computer but when I deploy to the server and attempt to run from there, I receive the following error:

Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

 

Here is the sample code that generates the above error.

 

Public Function SayHello() As String
      Dim strAnswer as string
      Try
          Dim cnConn As New System.Data.SqlClient.SqlConnection
          cnConn.ConnectionString = strConnString
          cnConn.Open()
          cnConn.Close()
          cnConn = Nothing
          strAnswer = "Hello"
     Catch ex As Exception
          strAnswer = ex.message
     End Try

    Return strAnswer
   End Function

 

I would prefer not to have to create a seperate DLL for these routines as they aren't used anywhere else and are small in footprint.

Any suggestions?

Sheryl

 

View Replies !   View Related
System.Data.SqlClient.SqlException: Error Converting Data Type Numeric To Decimal.
Hi There,

I'm using C# to get a value for a DOUBLE precision variable, called "Length", from a textBox using the following line:

Length = Convert.ToDouble( txtLength.Text )

I'm also using the following lines to prepare my stored procedure call:

arParms[9] = new SqlParameter("@Length", SqlDbType.Decimal, 5);
arParms[9].Value = record.Length;

My stored procedure has the following parameter definition:

@Length decimal(9,3)

My problem is that if someone types a value bigger than 999999 in the textbox he will get for sure the following error:

System.Data.SqlClient.SqlException: Error converting data type numeric to decimal.

I don't know how to either make sql or C# to truncate the value or catch the exception to automatically assign 0 to the parameter.

Please Help.
Moshe

View Replies !   View Related
System.Data.SqlClient.SqlException: Syntax Error Converting The Varchar Value 'V' To A Column Of Data Type Int
 I am using  a stored procedure which returns a value of charecter datatype 'V' to the calling program.I am getting an sql exception System.Data.SqlClient.SqlException: Syntax error converting the varchar value 'V' to a column of data type inti didnot define any int datatype in my tablethis is my codeSqlCommand com = new SqlCommand("StoredProcedure4", connection);com.CommandType = CommandType.StoredProcedure;  SqlParameter p1 = com.Parameters.Add("@uname", SqlDbType.NVarChar);SqlParameter p2 = com.Parameters.Add("@opwd", SqlDbType.NVarChar);SqlParameter p3 = com.Parameters.Add("@role", SqlDbType.NVarChar);p3.Direction = ParameterDirection.ReturnValue;p1.Value = username.Text.Trim();p2.Value = password.Text.Trim();com.ExecuteReader();lblerror2.Text = (string)(com.Parameters["@role"].Value); can your figure out what is the error ? Is it a coding error or error of the databse

View Replies !   View Related
Unable To Cast COM Object Of Type 'ADODB.CommandClass' To Interface Type 'ADODB._Command'
I have an application which runs successfully on a couple of my customer's machines but fails on a third.  It seems to fail when opening the database:

Unable to cast COM object of type 'ADODB.CommandClass' to interface type 'ADODB._Command'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{B08400BD-F9D1-4D02-B856-71D5DBA123E9}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=false; Initial Catalog=lensdb;Data Source = SQL

Before I got this error I was getting another problem (sorry didn't make a copy of that error's text) that made me think that adodb.dll simply wasn't loaded/registered.   I got rid of that error by copying my adodb.dll onto the third machine and running gacutil /i.  There is now an entry in winntassemblies for adodb.

Just in case you think it could be an obvious registry problem: when I started getting the current error I thought that maybe the registry needed updating and I merged the following lines into onto the target machine (from my dev machine):

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOTInterface{B08400BD-F9D1-4D02-B856-71D5DBA123E9}]
@="_Command"

[HKEY_CLASSES_ROOTInterface{B08400BD-F9D1-4D02-B856-71D5DBA123E9}ProxyStubClsid]
@="{00020424-0000-0000-C000-000000000046}"

[HKEY_CLASSES_ROOTInterface{B08400BD-F9D1-4D02-B856-71D5DBA123E9}ProxyStubClsid32]
@="{00020424-0000-0000-C000-000000000046}"

[HKEY_CLASSES_ROOTInterface{B08400BD-F9D1-4D02-B856-71D5DBA123E9}TypeLib]
@="{EF53050B-882E-4776-B643-EDA472E8E3F2}"
"Version"="2.7"

[HKEY_LOCAL_MACHINESOFTWAREClassesInterface{B08400BD-F9D1-4D02-B856-71D5DBA123E9}]
@="_Command"

[HKEY_LOCAL_MACHINESOFTWAREClassesInterface{B08400BD-F9D1-4D02-B856-71D5DBA123E9}ProxyStubClsid]
@="{00020424-0000-0000-C000-000000000046}"

[HKEY_LOCAL_MACHINESOFTWAREClassesInterface{B08400BD-F9D1-4D02-B856-71D5DBA123E9}ProxyStubClsid32]
@="{00020424-0000-0000-C000-000000000046}"

[HKEY_LOCAL_MACHINESOFTWAREClassesInterface{B08400BD-F9D1-4D02-B856-71D5DBA123E9}TypeLib]
@="{EF53050B-882E-4776-B643-EDA472E8E3F2}"
"Version"="2.7"


but, no change alas.

All three machines are running Windows 2000.

Any advice would be appreciated.

Thanks in advance,

Ross

View Replies !   View Related
How To Fix Unable To Cast Object Of Type 'Microsoft.SqlServer.Management.Smo.Urn'
In Sql Server 2005, Sql Server Mangerment Studio 9.00.1399.00
 I connected an user instance to the databases under .SQLEXPRESS(SqlServer 9.0.3042 -....)
when I right click on a table
and chose modify, or new table...
I get

TITLE: Microsoft SQL Server Management Studio
------------------------------
Unable to cast object of type 'Microsoft.SqlServer.Management.Smo.Urn' to type 'Microsoft.SqlServer.Management.Smo.Urn'. (SQLEditors)
------------------------------
BUTTONS:
OK
------------------------------

same thing for views
What can I do to fix the problem? is there a patch?

 
 
btw script .... as seem to be  erro free Error free is also View dependence,

View Replies !   View Related
Open SSIS Project Error: Unable To Cast COM Object Of Type
When I open up my existing SSIS project, I always get this error.  Does anyone know what was wrong ?

 

TITLE: Microsoft Visual Studio
------------------------------

Unable to cast COM object of type 'Microsoft.SqlServer.Dts.Runtime.Wrapper.PackageNeutralClass' to interface type 'Microsoft.SqlServer.Dts.Runtime.IObjectWithSite'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{FC4801A3-2BA9-11CF-A229-00AA003D7352}' failed due to the following error: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)).

 

View Replies !   View Related
System.Data.SqlClient.SqlException: Invalid Object Name
I am getting this error message 
System.Data.SqlClient.SqlException: Invalid object name 'RacingHeritage'
I have noticed from other posts where the database owner is the login name
I rebuilt the table and the owner is now dbo
Here is the Code 
   Function GetCustomers() As System.Data.DataSet        Dim connectionString As String = Application("HiddenConnection")        Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)
        Dim queryString As String = "SELECT [RacingHeritage].[RHID], [RacingHeritage].[UserID], [RacingHeritage].[Clie"& _            "ntFirstName] FROM [RacingHeritage]"        Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand        dbCommand.CommandText = queryString        dbCommand.Connection = dbConnection
        Dim dataAdapter As System.Data.IDbDataAdapter = New System.Data.SqlClient.SqlDataAdapter        dataAdapter.SelectCommand = dbCommand        Dim dataSet As System.Data.DataSet = New System.Data.DataSet        dataAdapter.Fill(dataSet)
        Return dataSet    End Function
Any Ideas

View Replies !   View Related
System.Data.SqlClient.SqlException: Invalid Object Name 'MESSAGE'.
i was deleting a row from my gridview.this fail  ("System.Data.SqlClient.SqlException: Invalid object name 'MESSAGE'.")   consists what must i do ?My SQL query is "UPDATE    MESSAGESET              DELETIONSTATUSTO = 1,_LASTMODIFYDATE =getdate() WHERE     (_ID = @ID)"  

View Replies !   View Related
'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Fail
I have a report that uses some embedded custom code. The embedded custom code is a function that execute some sql query on a sql server database.Everything works fine in Visual studio. The report gets deployed on the server successfully, however when  running the report from report manager i get the following error message : 

 

The Hidden expression for the table €˜table1€™ contains an error: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. 





 







 

Here is the code :

************************************************************************

Public function get_field() as string
Dim myConnection As System.Data.SqlClient.SqlConnection
Dim myCommand As System.Data.SqlClient.SqlCommand
Dim data_reader As System.Data.SqlClient.SqlDataReader
Dim field(100) as string
Dim i as integer
Dim j as integer
Dim sql_field as string
Dim nbr_field as integer
Dim rtn_string as string


i = 0
sql_field ="Select field from mytable" 
myConnection = New System.Data.SqlClient.SqlConnection("Datasource=xxx.xxx.xxx.xxmydatabase;Initial Catalog=mydatabase;User Id=user1;Password=password1;")
myConnection.Open()
myCommand = New System.Data.SqlClient.SqlCommand(sql_field, myConnection)
data_reader = myCommand.ExecuteReader()
While data_reader.Read()
 if data_reader.HasRows then
 field(i)=  data_reader(0).ToString()
               end if
nbr_field = nbr_field + 1
i= i+1
End While
data_reader.Close()
myConnection.Close()


for j = 0 to nbr_field -1
rtn_string = rtn_string + field(j) + "," 
Next j

rtn_string = left(rtn_string,rtn_string.length-1)
return  rtn_string
'return  sql_cmd
'return yes_no
'return lkupfield
end function

******************************************************************

Why do i get the error message ?, is this related to Code Access Security issues with .net framework. if yes

how do i set the Security so the report server or report manager allows embedded custom code to be executed. Any advice ?

 

Chi

 

 

 


 

View Replies !   View Related
Could Not Load Type 'System.Data.SqlServerCe.SqlCeDataAdapter' From Assembly 'System.Data.SqlServerCe'
 

Hi,

I am trying to make a mobile application work, but I get the following error. The operating system on Pocket PC is Microsoft® Windows Mobile„¢ 2003 Second Edition. Any ideas? Thanks in advance.

The followings are the error and my codes:

System.TypeLoadException was unhandled
  Message="Could not load type 'System.Data.SqlServerCe.SqlCeDataAdapter' from assembly 'System.Data.SqlServerCe, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91'."
  StackTrace:
    at SQLMobile.Form1.Form1_Load()
    at System.Windows.Forms.Form.OnLoad()
    at System.Windows.Forms.Form._SetVisibleNotify()
    at System.Windows.Forms.Control.set_Visible()
    at System.Windows.Forms.Application.Run()
    at SQLMobile.Form1.Main()

 

Codes:

Private Sub FillGrid()

Dim filename As New String _

("Program FilesSQLMobilesqlmobile.sdf")

Dim conn As New SqlCeConnection("Data Source=" + filename)

Dim selectCmd As SqlCeCommand = conn.CreateCommand()

selectCmd.CommandText = "select Destination from flightdata"

Dim adp As New SqlCeDataAdapter(selectCmd)

Dim ds As New DataSet()

adp.Fill(ds)

DataGrid1.DataSource = ds

End sub

View Replies !   View Related
Request For The Permission Of Type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken
Reporting services is configured to use a custom security extension in the following Environment.

Windows xp

IIS 5.0

when i go to http://servername/reports , the UIlogon.aspx page loads fine and i enter username and password. but i get logon failed.

when i go to http://servername/reportserver , the logon.aspx does not load and i get the following error message :

"Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."

any idea ? .

chi

 

View Replies !   View Related
Msg 6522, Level 16, State 2, Line 1: System.InvalidCastException: Conversion From Type 'SqlBoolean' To Type 'Boolean' Is Not Val
I created a function called Temperature in VB to be used as a UDF in SQL2005. I get the error listed below. Any thoughts?
 

CREATE FUNCTION Temperature(@FluidName SQL_variant, @InpCode SQL_variant, @Units SQL_variant, @Prop1 SQL_variant, @Prop2 SQL_variant)

RETURNS Float

AS EXTERNAL NAME Fluids_VB6.[Fluids_VB6.FluidProperties.Fluids].Temperature
 
Then ran function:
 

select dbo.temperature('R22','t','e','225.6','0')
 
Got this:
 

Msg 6522, Level 16, State 2, Line 1

A .NET Framework error occurred during execution of user defined routine or aggregate 'Temperature':

System.InvalidCastException: Conversion from type 'SqlBoolean' to type 'Boolean' is not valid.

System.InvalidCastException:

at Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object Value)

at Fluids_VB6.FluidProperties.Fluids.Setup(Object& FluidName)

at Fluids_VB6.FluidProperties.Fluids.CalcSetup(Object& FluidName, Object& InpCode, Object& Units, Object& Prop1, Object& Prop2)

at Fluids_VB6.FluidProperties.Fluids.CalcProp(Object& FluidName, Object& InpCode, Object& Units, Object& Prop1, Object& Prop2)

at Fluids_VB6.FluidProperties.Fluids.Temperature(Object FluidName, Object InpCode, Object Units, Object Prop1, Object Prop2)
 
Thanks
 
Buck

View Replies !   View Related
Cannot Convert Type 'int' To 'System.Data.DataView'
I have the following SqlDataSource in my page:<asp:SqlDataSource ID="sqlds" runat="server" ConnectionString="<%$ ConnectionStrings:cs %>"    SelectCommand="SELECT [Quest1], [Quest2], [Quest3], [Quest4], [Quest5] WHERE ([QuestID] = @QuestID)">    <SelectParameters>        <asp:Parameter Name="QuestID" />    </SelectParameters> In my code I get the following error: "Cannot convert type 'int' to 'System.Data.DataView'", I don't understand why I am getting this error because I am casting my SqlDataSource as type DataView when passing it to my DataView type.Code: protected void Chart(string record)    {        System.Data.DataView dv = (System.Data.DataView)sqlds.SelectParameters.Add("QuestID", System.TypeCode.Int32, record); //Error line       ...       ...       ...}If anyone could point me in the right direction I would be very grateful. 

View Replies !   View Related
System.Data.SqlClient.SqlError: Cannot Open Backup Device '\.Tape0'. Operating System Error 5(error Not Found). (Microsoft.Sql
System.Data.SqlClient.SqlError: Cannot open backup device '\.Tape0'. Operating system error 5(error not found). (Microsoft.SqlServer.express.Smo)
 
i have only one sql instance and tape is istalled successfully.
please help me to find solution for this error.
 
Thanks,

View Replies !   View Related
Cannot Pass Params (data Type System.guid) To Subreport?
Hello experts,

I am trying to create a report including a subreport in VS.2003 Reporting services. The subreport itself runs properly, if I give it a parameter, but when I try to run the main (parent) report, I get the obvious message Subreport could not be shown.

The output windows returns a message:

The value expression used in textbox €˜AccountID€™ returned a data type that is not valid.

The AccountID field is a system.guid. I tried to "cast" it as a text, but I got another error message that the system.guid cannot be explicitly converted.

Does anyone know how to get around this?

Thank you very much.

Ravie.

View Replies !   View Related
Could Not Load Type 'System.Data.Sqlserverce.sqlcecommand' Error In A PDA Application
 

Hi,
 
I am developing a Application using SQLCE Database & VS 2005 for Intermec CN3 PDA
It is having Windows Mobile 5.0 OS and ARM920T PXA27x Processor.
 
I have already installed
Microsoft .NET CF 2.0,
Microsoft SQL Client 2.0 ( using %Program Files%Microsoft SQL Server Compact Editionv3.1SDKinwce500armv4isqlce30.wce5.armv4i.CAB file) in PDA
 
I could able to run the application in the development environment which is having
Windows XP OS.
Microsoft .NET Compact framework 2.0,
SQL Server 2005 Compact edition
 
But when I  deploy the application in the PDA thro' cab file and try to run the application I am getting the below error at run time.
 
Could not load type
'System.Data.Sqlserverce.sqlcecommand' from assembly System.Data.Sqlserverce, version=9.0.242.0,culture=neutral,PublickeyToken=8984...'
 
I have added the SQLCE.dll from the below location
 
%Program Files%Microsoft SQL Server Compact Editionv3.1System.Data.SqlServerCe.dll
 
Anybody can suggest me to solve this issue.
 
Thanks in advance
 
With Regards,
D.Karthikeyan

View Replies !   View Related
CS0266: Cannot Implicitly Convert Type 'object' To 'bool'. An Explicit Conversion Exists (are You Missing A Cast?)
Using OnSelected on the SqlDataSource----here is my currect code:private void On_Load(Object sender, SqlDataSourceCommandEventArgs e){if (e.Command.Parameters["@DueDate"].Value = "NULL"){e.Command.Parameters["@DueDate"].Value = "0000-00-00 00:00:00.000";}}
I am trying to change the value from  NULL(in a datetime field) to "0000-00-00 00:00:00.000" for use on the page.Any ideas, suggestions, or thoughts would be greatly appreciated!
,Gary"we truly fail, only when we quit."

View Replies !   View Related
System.Data.SqlClient
 
I am not able to add the namespace "system.data.SqlClient"  and not able to get the intellisense for sqlconnections. I have only vs2005.  i do not have sql management express
or sql server 2005
 

View Replies !   View Related
System.Data.sqlclient
 
i have installed visual express and sql express.
but the problem is  i want to add the connection string manuallty in visual studio express 2005.
so i want to add a reference of sql.data.sqlclient but could not add ?
i am not sure what is the problem or is am i missing anything
 

View Replies !   View Related
System.Data.SqlClient.SqlException
When i am trying to connect to a SqlServer 2000 database from VS.Net 2.0 i am getting the following error:An attempt to attach an auto-named database for file c:inetpubwwwrootcasterVBApp_Dataaspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.So what is this aspnetdb.mdf  file?

View Replies !   View Related
System.Data.SqlClient.SqlException :( -- Please Help
Hi All,

I am new to ASP.NET and trying to learn. I am getting the problem when I try to insert data into SQL. The exception that I am getting is

Exception Details: System.Data.SqlClient.SqlException: An explicit value for the
identity column in table 'Customers' can only be specified when a column list is used and IDENTITY_INSERT is ON.

My table name is 'Customers' and its as below.
-----------------------------------------------------------------------
CustomerID--numeric---Identity Seed is 1000---Identity Increment is 1---No Nulls.
Name--------varchar---No Nulls.
address------Varchar---No Nulls.
State--------Varchar---No Nulls.
Zip-----------VarcHar---No Nulls.
PhoneNumber-Varchar---No Nulls.
Email---------Varchar---No Nulls.

and my code is (No fun of my code please--I am a learner)
-----------------------------------------------------------------------

Imports System.Data

Imports System.Data.SqlClient

Public Class register

Inherits System.Web.UI.Page

Protected WithEvents cnNWind As SqlConnection

'Protected drCustomers As SqlDataReader

Protected WithEvents lbladd As System.Web.UI.WebControls.Label

Protected WithEvents lblState As System.Web.UI.WebControls.Label

Protected WithEvents lblcity As System.Web.UI.WebControls.Label

Protected WithEvents lblzip As System.Web.UI.WebControls.Label

Protected WithEvents lblPhone As System.Web.UI.WebControls.Label

Protected WithEvents lblEmail As System.Web.UI.WebControls.Label

Protected WithEvents TxtName As System.Web.UI.WebControls.TextBox

Protected WithEvents txtAdd As System.Web.UI.WebControls.TextBox

Protected WithEvents txtState As System.Web.UI.WebControls.TextBox

Protected WithEvents txtCity As System.Web.UI.WebControls.TextBox

Protected WithEvents txtZip As System.Web.UI.WebControls.TextBox

Protected WithEvents txtPhone As System.Web.UI.WebControls.TextBox

Protected WithEvents TxtEmail As System.Web.UI.WebControls.TextBox

Protected WithEvents BtnSubmit As System.Web.UI.WebControls.Button

Protected WithEvents Label1 As System.Web.UI.WebControls.Label

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.

<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

End Sub

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init

'CODEGEN: This method call is required by the Web Form Designer

'Do not modify it using the code editor.

InitializeComponent()

End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Put user code to initialize the page here

End Sub

Private Sub BtnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSubmit.Click

cnNWind = New SqlConnection()

cnNWind.ConnectionString = "Data Source=(local); Initial Catalog=cart; Integrated Security=SSPI"

cnNWind.Open()

If cnNWind.State = ConnectionState.Open Then

Dim cmCustomers As New SqlCommand("INSERT INTO Customers VALUES ('',' " & TxtName.Text & "','" & txtAdd.Text & "','" & txtState.Text & "','" & txtZip.Text & "','" & txtPhone.Text & "','" & TxtEmail.Text & "')", cnNWind)

cmCustomers.ExecuteNonQuery()

cmCustomers.ExecuteNonQuery()

cnNWind.Close()

End If

End Sub

End Class

The Error I am getting:
-----------------------------------------------------------------------
Server Error in '/SCart' Application.
--------------------------------------------------------------------------------

An explicit value for the identity column in table 'Customers' can only be specified when a column list is used and IDENTITY_INSERT is ON.
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: An explicit value for the identity column in table 'Customers' can only be specified when a column list is used and IDENTITY_INSERT is ON.

Source Error:


Line 46: If cnNWind.State = ConnectionState.Open Then
Line 47: Dim cmCustomers As New SqlCommand("INSERT INTO Customers VALUES ('','" & TxtName.Text & "','" & txtAdd.Text & "','" & txtState.Text & "','" & txtZip.Text & "','" & txtPhone.Text & "','" & TxtEmail.Text & "')", cnNWind)
Line 48: cmCustomers.ExecuteNonQuery()
Line 49: cnNWind.Close()
Line 50: End If


Source File: d:inetpubwwwrootSCart
egister.aspx.vb Line: 48

Stack Trace:


[SqlException: An explicit value for the identity column in table 'Customers' can only be specified when a column list is used and IDENTITY_INSERT is ON.]
System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
SCart.register.BtnSubmit_Click(Object sender, EventArgs e) in d:inetpubwwwrootSCart
egister.aspx.vb:48
System.Web.UI.WebControls.Button.OnClick(EventArgs e)
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain()

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573


The code works fine If I Dont use Identity Column, But I need to use Identity Column in my Project :( ...Please Help.

View Replies !   View Related
How To Create A System Type Table/ Change User Table To System Table.
Is there any Posibility to change a User Table to System Table.

How to create one system table.

I am in Big mess that One of the Table I am using is in System Type.

I cant Index the same. Is there any Mistake we can change a user table to system table.....

View Replies !   View Related
'((System.Exception)($exception)).Message' Threw An Exception Of Type 'System.NotSupportedException'
Greetings everyone, I am attempting to build my first application using Microsofts Sql databases. It is a Windows Mobile application so I am using Sql Server Compact 3.5 with Visual Studio 2008 Beta 2. When I try and insert a new row into one of my tables, the app throws the error message shown in the title of this topic.
'((System.Exception)($exception)).Message' threw an exception of type 'System.NotSupportedException'
 

 
My table has 4 columns (i have since changed my FavoriteAccount datatype from bit to Integer)
http://i85.photobucket.com/albums/k71/Scionwest/table.jpg
 
Account type will either be "Checking" or "Savings" when a new row is added, the user will select what they want from a combo box.
 
Next is a snap shot of my startup form.
http://i85.photobucket.com/albums/k71/Scionwest/form.jpg

 
 
Where it says "Favorite Account: None" in the top panel, I am using a link label. When a user clicks "None" it will go to a account creation wizard, and set the first account as it's primary/favorite. As more accounts are added the user can select which will be his/her primary/favorite. For now I am just creating a sample account when the label is clicked in an attempt to get something working. Below is the code used.
 

private void lnkFavoriteAccount_Click(object sender, EventArgs e)

{

FinancesDataSet.BankAccountRow account = this.financesDataSet.BankAccount.NewBankAccountRow();

account.Name = "MyBank Checking Account";

account.AccountType = "Checking";

account.Balance = Convert.ToDecimal("15.03");

account.FavoriteAccount = 1;//datatype is an integer, I have changed it since I took the screenshot.

financesDataSet.BankAccount.Rows.Add(account);
//The next three lines where added while I was trying to get this to work.
//I don't know if I really need them or not, I receive the error regardless if these are here or not.



this.bankAccountTableAdapter1.Update(financesDataSet);

this.financesDataSet.AcceptChanges();

refreshDatabase();

}

 
the refreshDatabase() code is here:
 

private void refreshDatabase()

{

this.bankAccountTableAdapter1.Fill(this.financesDataSet.BankAccount);

//Aquire a count of accounts the user has

int numAccounts = financesDataSet.BankAccount.Count;

//Loop through each account and see which one is the primary.

for (int num = 0; num != numAccounts; num++)

{
//Works ok in frmMain_Load, but when my lnkFavoriteAccount_click calls this, it throws the error.

if (this.financesDataSet.BankAccount[num].FavoriteAccount == 1)

{
//Display the primary account on our home page. User can click the link label & be taken to their account register.

this.lnkFavoriteAccount.Text = this.financesDataSet.BankAccount[num].Name.ToString();

this.lnkFavoriteFunds.Text = this.financesDataSet.BankAccount[num].Balance.ToString();

break;

}

}

}

 
and my form_load code

private void frmMain_Load(object sender, EventArgs e)

{

refreshDatabase();

}

 
So, when I click on the lnkFavoriteAccount label, and my new row gets added, the app stops at the following line in my DataSet.Designer

[global:ystem.Diagnostics.DebuggerNonUserCodeAttribute()]

public byte FavoriteAccount {

get {

try {

return ((byte)(this[this.tableBankAccount.FavoriteAccountColumn]));

}

catch (global:ystem.InvalidCastException e) {
//Stops at the following line, this error was caused by 'if (this.financesDataSet.BankAccount[num].FavoriteAccount == 1)'

throw new global:ystem.Data.StrongTypingException("The value for column 'FavoriteAccount' in table 'BankAccount' is DBNull.", e);

}

}

set {

this[this.tableBankAccount.FavoriteAccountColumn] = value;

}

}

 
I have no idea what I am doing wrong, all of the code I used I retreived from Microsofts help documentation included with VS2008. I have tried used my TableAdapter.Insert() method and it still failed when it got to

if (this.financesDataSet.BankAccount[num].FavoriteAccount == 1)

in my refreshDatabase() method it still failed.
 
When I look, the data has been added into the database, it's just when I try to retreive it now, it bails on me. Am I retreiving the information wrong?
 
Thanks for any help you guys can offer.
 
Johnathon

View Replies !   View Related
-- Please Help System.Data.SqlClient.SqlClientPermission Problem ---
im getting this error when i try to access the application from the network. but in my computer work fine
 
Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
please help... thanxs

View Replies !   View Related
ADODB Vs SQLConnection (System.Data.SqlClient)
Hi all,
Data access modules of my ASP.NET 2.0 app. are mostly written using SQLConnetion of System.Data.SqlClient. Everything has been working fine until I start using a third party ASP.NET mapping control, AspMap, which uses ADODB for data access.
Whenever I run the AspMap page without accessing any of the pages using SQLConnetion, things are fine. However, whenever I run the AspMap Page after having accessed any page that uses SQLConnection, I would get the folowing error without fail:
Unable to open the physical file "C:WebSitesARS_WebsiteApp_DataAppData.mdf". Operating system error 32: "32(The process cannot access the file because it is being used by another process.)".
And the interesting is that - everytime when run my app. I can see an instance created for my AppData.mdf database using the Microsoft SQL Sever Management Studio Express. And when I detete that database instance manually and run the AspMap right away, it would work.
My guess is that the key to the solution to my problem is to how to detach the database from within my C# web app. Any pointers would be greated appreciated.
By the way, I have made sure that all connections using SQLConnection in app. was properly closed and disposed off when they are not needed anymore.
Here are some of my plaftform detais:
Programming tool: Visual Web Developer Express Edition
Database Server: SQL Server 2005 Express Edition
Language used: C#
OS: Windows XP Professional
Regards,
Sai Huan

View Replies !   View Related
System.Data.SqlClient.ConnectionPool.CreateConnection
 

Hi,

I had make one Desktop application in VB.net, having 6 threads simultaneously running. And each thread connect to sql server and stored the value in DB at every one second. Now my problem is that when I start the application its working fine but after 20-30 minutes exception is occuring.

Login failed for user 'sa'.
Exception StackTrace:
   at System.Data.SqlClient.ConnectionPool.CreateConnection()
   at System.Data.SqlClient.ConnectionPool.PoolCreateRequest(Object state)

can anybody help me

- Hiren

View Replies !   View Related
The Type Or Namespace Name 'SqlServer' Does Not Exist In The Namespace 'System.Data'
Hi,
I have created a .net class library and i include the namespace :
using System.Data.SqlServer
but when i build my .net class library i get the folowing error:
The type or namespace name 'SqlServer' does not exist in the namespace 'System.Data' (are you missing an assembly reference?) 
 
your help is highly appreciated
Best regards

View Replies !   View Related
'System.Web.NativeFileChangeNotification' To Type 'DecompressInitDelegate'.
I started getting this error, strangely, in SSRS when processing an updated report:


 

 

 








An error has occurred during report processing.

Cannot create a connection to data source 'AnalysisServices'.

Unable to cast object of type 'System.Web.NativeFileChangeNotification' to type 'DecompressInitDelegate'.                                                                  


























Has anyone seen this issue or know how to resolve it?

View Replies !   View Related
Strange SQL Error System.Data.SqlClient.SqlException
Hi there, i copied some insert code from one page to another and it keeps throwing me this error, i was wondering if anyone can help me out. Here is the error
System.Data.SqlClient.SqlException: The name "Credit" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Admin_expenses.Button1_Click(Object sender, EventArgs e) in d:hostingmemberashdfhtdocswwwAdminexpenses.aspx.cs:line 40
 This is my code, i cant see anything obvious and as i said i just copied it across, the only things changed were the names and the sqlstringprotected void Button1_Click(object sender, EventArgs e)
{decimal intamount = Convert.ToDecimal(txtAmount.Text);
string sConnectionStringExpense = "Data Source=xxxx;Initial Catalog=xxxx;User ID=xxxx;Password=xxxx";SqlConnection objConnExpense = new SqlConnection(sConnectionStringExpense);
 using (objConnExpense)
{
objConnExpense.Open();string sqlExpense = "INSERT INTO tbl_expenses (expense_amount, expense_payment_type, expense_type, expense_description) " +
"VALUES (" + intamount + "," + ddlPaymentType.SelectedItem + "," + ddlExpenseType.SelectedValue + "," + txtDescription.Text + ")";SqlCommand objCmdExpense = new SqlCommand(sqlExpense, objConnExpense);
try
{
objCmdExpense.ExecuteNonQuery();
}catch (Exception ex)
{lblcomplete.Text = "!!Adjust stock for product at location " + Convert.ToString(ex);
}
finally
{
objConnExpense.Close();
}
}

View Replies !   View Related
Is System.Data.SqlClient Still The Default Provider For The SqlDataSource?
While learning ASP.net 2.0, I was taught that the the default provider for the SqlDataSource was System.Data.SqlClient, and that I only needed to specify it as a provider when I put it in the web.config file. However, now (in VWDE 2008) when I add a SqlDataSource to a page, it adds ProviderName="System.Data.SqlClient". Does this mean that it isnt the default anymore?

View Replies !   View Related
System.Data.SqlClient.SqlException: Incorrect Syntax Near '&>'.
I keep getting this error whenever I try to run my query:   System.Data.SqlClient.SqlException: Incorrect syntax near '>'.
I'm just trying to fill a  dataset with three tables that contain the past few days headlines...what am I doing wrong?? Private Sub fishHeadlines()
Dim dateNow As DateTime = DateTime.Now()Dim dateThen As DateTime = DateTime.Today.AddDays(-2)
'create the table array so we can create the sql statement in a moment
Dim table() As Stringtable = New String() {"Snapper", "Scissor", "MahiMahi"}
Dim strSelect As String
'Create a dataset to hold the tables containing the headlinesDim headlinesDS As New DataSet()
'create the connection string - SnapshotConnectionString is in web.config file
Dim strConnect As StringstrConnect = ConfigurationManager.ConnectionStrings("fishConnectionString").ConnectionString
'create a connection object to the databaseDim objConnect As New SqlConnection(strConnect)
objConnect.Open()
Dim i As Integer
'fill the datatablesFor i = 0 To table.Length
strSelect = "SELECT Event FROM " & table(i) & "WHERE (DateOfEntry > '" & dateThen & "')"
'create a data adapter object using connection and sql statementsDim objDA1 As New SqlDataAdapter(strSelect, objConnect)
'fill the dataset
objDA1.Fill(headlinesDS, table(i))
Next
Dim strTable As StringDim dr As DataRow
strTable = "<table>"For i = 0 To table.Length
For Each dr In headlinesDS.Tables(table(i)).Rows
strTable += "<tr><td>" & dr(0).ToString() & "</td></tr>"
Next
Next
strTable += "</table>"
'display the data
lblHeadlines.Text = strTable
End Sub

View Replies !   View Related
System.Data.SqlClient.SqlException: SSL Security Error
Hello,
we have asp.net apps on a windows 2003 server that connect to an instance of sql server 2005 enterprise edition on another windows 2003 server.  We get this error at random times.  Anyone know what could be causing it?
 
System.Web.HttpUnhandledException: Exception of type System.Web.HttpUnhandledException was thrown. ---> System.Data.SqlClient.SqlException: SSL Security error.   at System.Data.SqlClient.ConnectionPool.GetConnection(Boolean& isInTransaction)   at System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConnectionString options, Boolean& isInTransaction)   at System.Data.SqlClient.SqlConnection.Open()Thanks

View Replies !   View Related
System.Data.SqlClient.SqlException - When Inserting Image
Hi All,
I have a form (asp website with the default.aspx and default.aspx.cs) which I use to connect to the SQL Server 2005 database and insert, update,get and delete data to and from it. In the table I have a column called Picture to insert a photo (usually bmp files) which I declared as a varbinary(max). ID is the primary key and is an int (i tried it to be numeric & varchar).
I am trying to insert data into the table using a form with this syntax:
SqlConnection enter_conn = new SqlConnection("user id=;" +
"password=;server=servername;" +
"Trusted_Connection=yes;" +
"database=Member Profiles; " +
"connection timeout=30");
enter_conn.Open();
string insertSql = "Insert dbo.Details(ID,Last_Name,First_Name,Middle_Initial,Project, Organization,Manager,Current_Skills,Biography,Hobbies, Picture) Select 1001, 'ABC','XYZ','R',' Website Development','ACT',LKM','ASP.Net, C#.Net, SQL Server 2005, SharePoint, Java, ',' developing the new website for ACT using SharePoint and SQL Server 2005', ' Singing, Listening to Music, Dancing, Cooking, Swimming', BulkColumn from Openrowset( Bulk 'C:\photos\rose.bmp', Single_Blob) as Picture";


SqlCommand myCommand = new SqlCommand(insertSql, enter_conn);
int i = myCommand.ExecuteNonQuery();
 
 I have no data in the table and am doing the first insert. Though the data gets inserted I am getting this exception:
System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_Details'. Cannot insert duplicate key in object 'dbo.Details'. The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at _Default.Enter_Click(Object sender, EventArgs e) in c:Documents and SettingskrkondaXMy DocumentsVisual Studio 2005WebSitesMember ProfilesDefault.aspx.cs:line 82
 
Can someone please suggest anything???? I appreciate a quick response please!!!!
 
Thanks,
Kavya

View Replies !   View Related

Copyright © 2005-08 www.BigResource.com, All rights reserved