Sqldatareader Is Not Defined Error

Oct 5, 2005

HiI try to retriveing data from database using following code (code-behind page). then put data into form fields. It tells me SqlDataReader is not defined. What does this mean? I am using Visual Studio.net and new to it. Please help. thnaks.---------------------------------------------------------------------------------------Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load



Dim myReader As SqlDataReader = myCommand.ExecuteReader()

If myReader.HasRows Then

Do While myReader.Read()

txtfname.Text = myReader("fname")

txtlname.Text = myReader("lname")

Loop

Else

Console.WriteLine("No rows returned.")

End If

myReader.Close()

End Sub

View 7 Replies


ADVERTISEMENT

The Type 'System.Data.SqlClient.SqlDataReader' Has No Constructors Defined

Sep 23, 2006

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

The Type 'System.Data.SqlClient.SqlDataReader' Has No Constructors Defined

May 21, 2008

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

Dim Rd As SqlDataReader Error

May 18, 2008

good afternoon everybody
 
this is my code: and their is an error ,,really dunno where and why coz it seems logical to me :)Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If RadioButton1.Checked = True Then
 
Dim admin As Stringadmin = "SELECT * from ADMINISTRATOR where UserName='" & TextBox1.Text & "' and UserPassword='" & TextBox2.Text & "'"
 
Dim sConnect As String = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True"Dim cnt As New SqlConnection
cnt.ConnectionString = sConnect
cnt.Open()Dim com As New SqlCommand
com.Connection = cnt
com.CommandText = adminerror!!>>>>Dim rd As SqlDataReader
rd = com.ExecuteReader
If rd.Read ThenSession("admn") = rd("UserName")Session("id") = rd("UserID")
rd.Close()
cnt.Close()Response.Redirect("~/adminpage.aspx")
ElseSession("admn") = 0
Label3.Visible = True
rd.Close()
cnt.Close()
End If
Else
Dim instrct As Stringinstrct = "SELECT * from instructor where name='" & TextBox1.Text & "' and passs='" & TextBox2.Text & "'"
 
Dim sConnect As String = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True"Dim con As New SqlConnection
con.ConnectionString = sConnect
con.Open()Dim com As New SqlCommand
com.Connection = con
com.CommandText = instrctDim r As SqlDataReader
r = com.ExecuteReader
If r.Read ThenSession("inst") = r("inst_name")
r.Close()
con.Close()Response.Redirect("~/instructorpage.aspx?id=" & Session("inst"))
ElseSession("inst") = 0
Label3.Visible = True
r.Close()
con.Close()
End If
End If
End Sub
-----------------
this is the error line:
The data types text and varchar are incompatible in the equal to operator.
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: The data types text and varchar are incompatible in the equal to operator....
so,,,any  suggestions? 

View 2 Replies View Related

Odd Error Upon SqlDataReader.Read() Invalid Length Parameter Passed To The Substring Function.

Nov 12, 2003

An application I developed normally works great, but it seems that when processing a certian record (and none of the others so far), SQL Server throws this error:
"Invalid length parameter passed to the substring function."

Here's the code in question:

orderConnection.Open()
orderReader = orderCommand.ExecuteReader()
setControls(orderReader)

...

Private Sub setControls(ByVal dr As SqlDataReader)
If (dr.Read()) Then '<--*******problem line*******

The SqlDataReader (orderReader) doesn't blow up or anything until I call .Read() (and, as mentioned, this problem only occurs for one order). What could be happening here?

View 3 Replies View Related

Too Many Fields Defined Error When Previewing Xls

Jun 15, 2007

Anyone know why I am getting this?===================================

There was an error displaying the preview. (Microsoft Visual Studio)

===================================

Too many fields defined. (Microsoft JET Database Engine)

------------------------------
Program Location:

at Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask.Connections.SQLTaskConnectionOleDbClass.ExecuteStatement(Int32 resultType, Boolean isStoredProc, UInt32 dwTimeOut)
at Microsoft.DataTransformationServices.Design.PipelineUtils.ShowDataPreview(String sqlStatement, ConnectionManager connectionManager, Control parentWindow, IServiceProvider serviceProvider, IDTSExternalMetadataColumnCollection90 externalColumns)
at Microsoft.DataTransformationServices.DataFlowUI.DataFlowConnectionPage.previewButton_Click(Object sender, EventArgs e)

View 5 Replies View Related

Getting Error Type SqlConnection Is Not Defined...

Mar 10, 2008

I'm a noob to sql ce 3.5 and am getting the error "Type SqlConnection is not defined". I'm thinking this has something to do with the sql client not being installed but am not sure. I've tried adding - 'Imports System.Data.SqlClient' but it's not available, anyone ahave any ideas on how to fix this?

Thanks,

View 4 Replies View Related

Primary Key Is Defined, Need To Process Thrown Error:

May 28, 2004

Hello:

I have a database table where a primary key is defined. When I enter data that is the same as another table, it does not allow and throws an error which I do want. What happens is that a Server Error in Application error type is thrown with the following message:

Violation of PRIMARY KEY constraint 'PK_cs_sc'. Cannot insert duplicate key in object 'cs_sc'. The statement has been terminated.

How can I detect the error in my own asp.net page code so that it does not forward my users to the asp.net server error page? Heres my code below... how can I check for success or failure within this code?

Dim conSqlConnect As SqlConnection
Dim strInsert As String
Dim cmdInsert As Sqlcommand
conSqlConnect = New SqlConnection( "Server=localhost;uid=var;pwd=var;database=var" )
strInsert = "Insert cs_sc ( [name] ) Values ( @name )"
cmdInsert = New SqlCommand ( strInsert, conSqlConnect )
conSqlConnect.Open()
cmdInsert.ExecuteNonQuery()
conSqlConnect.Close()

View 3 Replies View Related

Error Notification From User Defined Function

Jul 23, 2005

Is there any reason why I shouldn't cause an arithmetic error(say bydividing by zero) in a User Defined Function for a situation where in astored procedure you would use RAISERROR or in code you would throw anexception?In most situations, I can check the return value of the UDF to see thatit is valid. However, I want to sum the output of UDF and thereforecannot check the return value. Errors should be so rare that I wouldrather not use a cursor to do the sum--and take the peformance hit.Following is the code:SELECT SUM([dbo].[udf_MyFunction]([Column1],[Column2]))FROM tblMyTableThanks ~ Matt

View 1 Replies View Related

Error 30002: Type 'Microsoft.Vsa.VsaModule' Is Not Defined

Apr 29, 2008



Hello,

I'm receiving the following error when executing a Script Task.


Error: 0x7 at Generate Snapshot: Error 30002: Type 'Microsoft.Vsa.VsaModule' is not defined.

Line 4 Columns 12-34

Line Text:


Has anyone seen this before? I'm creating the task to interact with our reporting server as prescribed in a separate thread. The actual code snippet is listed below. ReportingService2005 is a proxy class created by WSDL.EXE to provide an interface to the report services webservice.





Code Snippet
' Microsoft SQL Server Integration Services Script Task
' Write scripts using Microsoft Visual Basic
' The ScriptMain class is the entry point of the Script Task.
Imports System
Imports System.Data
Imports System.Math
Imports System.Xml
Imports System.Web.Services
Imports Microsoft.SqlServer.Dts.Runtime
Public Class ScriptMain
' The execution engine calls this method when the task executes.
' To access the object model, use the Dts object. Connections, variables, events,
' and logging features are available as static members of the Dts class.
' Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
'
' To open Code and Text Editor Help, press F1.
' To open Object Browser, press Ctrl+Alt+J.
Public Sub Main()
Dim rs As New Microsoft.SqlServer.ReportingServices2005.ReportingService2005
' Set the credentials
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
Try
' Retrieve package variable information
Dim reportName As String = Dts.variables("reportName").value.tostring()
Dim reportStatusID As Long = Dts.variables("reportStatusID").value
Dim environmentName As String = Dts.variables("environmentName").value.tostring()
' Define report location
Dim parentFolder As String = "ODRReports"
Dim parentPath As String = "/" & parentFolder
Dim reportPath As String = parentFolder & "/" & reportName
' Define report history parameters.
Dim EnableManualSnapshotCreation As Boolean = True
Dim KeepExecutionSnapshots As Boolean = False
Dim schedule As Microsoft.SqlServer.ReportingServices2005.NoSchedule
' Set the report history options.
rs.SetReportHistoryOptions(reportPath, EnableManualSnapshotCreation, _
KeepExecutionSnapshots, schedule)
' Update the report snapshot
rs.UpdateReportExecutionSnapshot(reportPath)
Dts.log("The execution snapshot for " & reportPath & " was created successfully", 0, x)
Catch ex As Exception
Dts.Log("Error: " & ex.Message & " " & ex.StackTrace, 0, x)
End Try
Dts.TaskResult = Dts.Results.Success
End Sub
End Class


Kind regards,
Orlanzo

View 6 Replies View Related

Problem About Error Handling In User Defined Function

Sep 14, 2007



i have a table in which there is a column of type varchar(20), containing a non-standard datetime string, so i wrote a user-defined function to convert this string to datetime value to do further work. the function first reformat the string so that sql server can recognize it and then use cast() function convert the reformatted string to datetime type.

at begining it works fine, but now i found that there might be some corrupted data in this daily-updated table, whos date string is unconvertable. so when i'm trying to process some date containing corrupted records, the string-to-datetime function breaks, reporting it has meet an converting error. i searched msdn and found that the tsql try..catch statement can't be used in user defined function. now i have no idea on how to solve this problem, is there anyone can help me? or is there any way to pick those corrupted rows out so i can throw them away? thanks

View 3 Replies View Related

Error 'Type 'SqlConnection' Is Not Defined' In VS2005/aspx.vb Files

Apr 17, 2008

 I defined the following connection string (strConn) and coded "Dim oConn As New SqlConnection(strConn)".In this VS 2005/ASP.net 2.0 program, 'SqlConnection' was underlined and showed 'Type SqlConnection is not defined' error. 
 What wrong with my VS 2005/ASPnet 2.0 coding, or SQL Server 2000 database configuration?
TIA,Jeffrey
connectionString="Data Source=webserver;Initial Catalog=Ssss;Persist Security Info=True;User ID=WWW;Password=wwwwwwww"providerName="System.Data.SqlClient"

View 3 Replies View Related

Parser Error Message: Security Level Already Defined For 'RosettaMgr'.

Mar 3, 2008

Hello All,

All of a sudden our reports stopped working today giving this error:


Server Error in '/Reports' Application.



Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Security level already defined for 'RosettaMgr'.

Source Error:





Line 21: <httpRuntime executionTimeout="9000"/>Line 22: <securityPolicy>Line 23: <trustLevel name="RosettaMgr" policyFile="rsmgrpolicy.config"/>Line 24: </securityPolicy>Line 25: <trust level="RosettaMgr" originUrl=""/>

Source File: C:Program FilesMicrosoft SQL ServerMSSQLReporting ServicesReportManagerweb.config Line: 23




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



If I comment out the lines 22 - 25 in the web.config file the reports start to work again, but I am reluctant to do this as I'm not sure what the implications would be if left..



Does anybody have any suggestions??



Many Thanks

View 1 Replies View Related

Error 30002: Type 'Microsoft.Vsa.VsaModule' Is Not Defined When Using Web Service

May 1, 2008



Hello,

I'm receiving the following error when executing a Visual Basic Script Task in SQL Server Integration Services. I've cross posted the same question there and have not received a solution regarding the error. I've also posted the message to the Visual Basic forum becuase multiple products are involved and I'm unsure where it is best suited.

The error occurs on multiple machines. I'm using Visual Studio 2005 and Reporting Services 2005. Has anyone encountered this error before?


Error: 0x7 at Generate Snapshot: Error 30002: Type 'Microsoft.Vsa.VsaModule' is not defined.

Line 4 Columns 12-34

Line Text: Microsoft.Vsa.VsaModule(True)>


I'm creating the task to interact with our reporting server as prescribed in a separate thread. I'm trying to generate a report snapshot using a web service for SQL Reporting Services. The actual code snippet is listed below. ReportingService2005 is a proxy class created by WSDL.EXE to provide an interface to the report services webservice.

Interestingly, the error does not occur when the proxy class is removed. I have added a reference to System.Web.Services and System.XML.





Code Snippet
' Microsoft SQL Server Integration Services Script Task
' Write scripts using Microsoft Visual Basic
' The ScriptMain class is the entry point of the Script Task.
Imports System
Imports System.Data
Imports System.Math
Imports System.Xml
Imports System.Web.Services
Imports Microsoft.SqlServer.Dts.Runtime
Public Class ScriptMain
' The execution engine calls this method when the task executes.
' To access the object model, use the Dts object. Connections, variables, events,
' and logging features are available as static members of the Dts class.
' Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
'
' To open Code and Text Editor Help, press F1.
' To open Object Browser, press Ctrl+Alt+J.
Public Sub Main()
Dim rs As New Microsoft.SqlServer.ReportingServices2005.ReportingService2005
' Set the credentials
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
Try
' Retrieve package variable information
Dim reportName As String = Dts.variables("reportName").value.tostring()
Dim reportStatusID As Long = Dts.variables("reportStatusID").value
Dim environmentName As String = Dts.variables("environmentName").value.tostring()
' Define report location
Dim parentFolder As String = "ODRReports"
Dim parentPath As String = "/" & parentFolder
Dim reportPath As String = parentFolder & "/" & reportName
' Define report history parameters.
Dim EnableManualSnapshotCreation As Boolean = True
Dim KeepExecutionSnapshots As Boolean = False
Dim schedule As Microsoft.SqlServer.ReportingServices2005.NoSchedule
' Set the report history options.
rs.SetReportHistoryOptions(reportPath, EnableManualSnapshotCreation, _
KeepExecutionSnapshots, schedule)
' Update the report snapshot
rs.UpdateReportExecutionSnapshot(reportPath)
Dts.log("The execution snapshot for " & reportPath & " was created successfully", 0, x)
Catch ex As Exception
Dts.Log("Error: " & ex.Message & " " & ex.StackTrace, 0, x)
End Try
Dts.TaskResult = Dts.Results.Success
End Sub
End Class


Here is a snippet of the ReportingServices2005 class created by WSDL.EXE and is being referenced by the above code.




Code Snippet
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.832
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict Off
Option Explicit On
Imports System
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml.Serialization
'
'This source code was auto-generated by wsdl, Version=2.0.50727.42.
'
Namespace Microsoft.SqlServer.ReportingServices2005

'''<remarks/>
<System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42"), _
System.Diagnostics.DebuggerStepThroughAttribute(), _
System.ComponentModel.DesignerCategoryAttribute("code"), _
System.Web.Services.WebServiceBindingAttribute(Name:="ReportingService2005Soap", [Namespace]:="http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices"), _
System.Xml.Serialization.XmlIncludeAttribute(GetType(DataSourceDefinitionOrReference)), _
System.Xml.Serialization.XmlIncludeAttribute(GetType(ExpirationDefinition)), _
System.Xml.Serialization.XmlIncludeAttribute(GetType(RecurrencePattern)), _
System.Xml.Serialization.XmlIncludeAttribute(GetType(ScheduleDefinitionOrReference))> _
Partial Public Class ReportingService2005
Inherits System.Web.Services.Protocols.SoapHttpClientProtocol

...

Public Sub New()
MyBase.New()
' Define the report server URL based on the environment name.
Select Case envName
Case Is = "Dev"
Me.Url = "http://m1waca0021/Reports$ODRDEV/ReportService2005.asmx"
Case Is = "QA"
Me.Url = "http://m1waca0020/ReportServer$ODRQA/ReportService2005.asmx"
Case Is = "PROD"
Me.Url = "http://msilsa0161/ReportsODR/ReportService2005.asmx"
Case Is = "LOCALDEV"
Me.Url = "http://localhost/ReportServer"
Case Is = Nothing
Me.Url = Nothing
End Select
End Sub






Kind regards,
Orlanzo

View 1 Replies View Related

User-defined Fun Or The System-defined Fun

Apr 2, 2008

hai,

how can i identify the function is user defined or the system defined function....................

View 1 Replies View Related

SQL 2012 :: NET Framework Error Occurred During Execution Of User-defined Routine Or Aggregate

Aug 4, 2015

when i try to deploy a packages in integration service catalog i am getting the below error

.NET Framework error occurred during execution of user-defined routine or aggregate

"deploy_project_internal":

System.ComponentModel.Win32Exception: A required privilege is not held by the client

System.ComponentModel.Win32Excepbon:

at Microsoft. SqlServer. IntegrationServices.Server.ISServerProcess.StartProcess(Soolean

bSuspendThread)

at Microsoft.SqlServer.IntegrationServices.Server.ServerApi.DeployProjectlnternal(SqlInt64 deployld,

SqIInt64 versionld, SqlInt64 projectld, SqlString projectName)

. (Microsoft SQL Server, Error: 6522)

View 0 Replies View Related

Expression Defined In SELECT Clause Overwrites Column Defined In FROM Clause

May 14, 2008

2 examples:

1) Rows ordered using textual id rather than numeric id


Code Snippet
select
cast(v.id as nvarchar(2)) id
from
(
select 1 id
union select 2 id
union select 11 id
) v
order by
v.id






Result set is ordered as: 1, 11, 2
I expect: 1,2,11


if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.

2) SQL server reject query below with next message

Server: Msg 169, Level 15, State 3, Line 16
A column has been specified more than once in the order by list. Columns in the order by list must be unique.




Code Snippet
select
cast(v.id as nvarchar(2)) id
from
(
select 1 id
union select 2 id
union select 11 id
) v
cross join (
select 1 id
union select 2 id
union select 11 id
) u
order by
v.id
,u.id




Again, if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.

It reproducible on

Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38 Copyright (c) 1988-2003 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)


and


Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86) Feb 9 2007 22:47:07 Copyright (c) 1988-2005 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)

In both cases database collation is SQL_Latin1_General_CP1251_CS_AS

If I check quieries above on database with SQL_Latin1_General_CP1_CI_AS collation then it works fine again.

Could someone clarify - is it bug or expected behaviour?

View 12 Replies View Related

Error-14010-remote Server Not Defined As Subscription Server

May 4, 2006

Running SQL Server Personal Ed (Server A) on Tablet PC (publication and distribution setup here) trying to push data to SQL Server 2000 Enterprise Ed. (Server B). When I start sync I get two failures. First is 'remote server not defined as subscription server'. Second, subscription to publication xx not valid (error# -2147201019). The snapshot is succeeding fine. What do I need to setup on Server B? I have the same db on both servers.

View 4 Replies View Related

How I Can Use SqlDataReader?

Nov 29, 2007

Hi..
 Every time I want to read any record from data base I read it in dataset for example:SqlConnection con = new SqlConnection(@"Data Source=localhost ;Initial Catalog=university ;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select [User_AuthorityID] from users where [UserID]='" + TextBox1.Text + "' and [UserPassword]='" + TextBox2.Text + "' ", con);SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;DataSet ds = new DataSet();
adp.Fill(ds, "UserID");foreach (DataRow dr in ds.Tables["UserID"].Rows)
{
user_type = dr[0].ToString();
Session.Add("User_AuthorityID", user_type);
.........
 Is there easier way to read data from data base?
How I can use SqlDataReader to do that?
 Thanks..

View 4 Replies View Related

SqlDataReader Within Another SqlDataReader - Can It Be Done?

Jun 1, 2008

Hey All,
I have come across a situation with two tables, they are dynamic and the user can add and edit values in the tables so I need to build a dynamic display control. It is all based around an FAQ system I have built. The user can create new FAQ categories (that is one table) then create a new FAQ Question & Answer (that is the second table). The tables are linked by the category id. So now I am trying to display the FAQ section like so.
CATEGORY NAME
QuestionAnswerQuestionAnswerCATEGORY NAME
QuestionAnswerQuestionAnswerCATEGORY NAME
QuestionAnswerQuestionAnswer
So my idea was to run a loop within a loop. First loop the category name, then within the category name, loop a second time to grab all of the questions & answers within the category id captured from the first loops sql select statement, then proceed to loop the category name again and of course repeat the process until all loops are completed. However I am getting, and I kinda figured I would get an error about my SQLDataReader. Bellow is my code maybe some type of edit or different recommendation is needed. Any help will do, thanks!Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'--- Database Connection ---Dim sConnStr As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim cnBKPost As New SqlConnection(sConnStr)
'--- End DB Connection ----
'----- FAQ's -------
Dim sql As String = "SELECT category_id, category_name FROM faq_category ORDER BY category_name DESC"Dim cmd As New SqlCommand(sql, cnBKPost)
cnBKPost.Open()Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim str As New StringBuilder()
Dim catid As IntegerDo While reader.Read()
'--- Category Titles ----catid = reader("category_id")
str.Append("<h2>" & reader("category_name") & "</h2>")
'--- End Category Title ---
'--- Get FAQ's In Category ---
Dim sqlcat As String = "SELECT faq_question, faq_answer FROM tbl_faq WHERE faq_category = '" & catid & "'"Dim cmdcat As New SqlCommand(sqlcat, cnBKPost)
Dim readerfaq As SqlDataReader = cmdcat.ExecuteReader()Do While readerfaq.Read()
str.Append("<p><font style='font-size:12pt;font-color:#daa520;>'" & reader("faq_question") & "</font><br />")str.Append(reader("faq_answer") & "</p>")
str.Append("<br /><br /><br />")
Loop
readerfaq.Close()
'--- End Get FAQ's in Category ---
Loop
reader.Close()
cnBKPost.Close()Me.Literal1.Text = str.ToString()
End Sub
End Class

View 2 Replies View Related

Using SqlDataReader

Jun 25, 2004

i'm using c# and SqlDataReader to simply retrieve data from one column of a database. problem is it's an integer i'm trying to retrieve, and so i'm trying to put it into an int variable, and i get the error "CS0029: Cannot implicitly convert type 'object' to 'int'" . i've looked for an answer for about an hour and every example for the SqlDataReader that i can find deals with strings only or the examples are too complex for me to understand.

there must be an easy way to retrieve this data and put it into an integer! help...

my line of code that creates the error:

int intGuestNum = dtrSelectTotalSessions["online_numSessions"];

View 5 Replies View Related

A .NET Framework Error Occurred During Execution Of User-defined Routine Or Aggregate -While Creating A SQL SERVER 2005 Stored Prodecure In VS.NET 2005

Aug 15, 2007

 Running [dbo].[insertlogin] ( @log = hiten, @pas = hiten ).A .NET Framework error occurred during execution of user-defined routine or aggregate "insertlogin": System.Data.SqlClient.SqlException: Must declare the scalar variable "@Log".System.Data.SqlClient.SqlException:    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)   at System.Data.SqlClient.SqlInternalConnectionSmi.EventSink.ProcessMessagesAndThrow(Boolean ignoreNonFatalMessages)   at Microsoft.SqlServer.Server.SmiEventSink_Default.ProcessMessagesAndThrow(Boolean ignoreNonFatalMessages)   at System.Data.SqlClient.SqlCommand.RunExecuteNonQuerySmi(Boolean sendToPipe)   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()   at SqlServerProject1.StoredProcedures.insertlogin(SqlString log, SqlString pas).No rows affected.(0 row(s) returned)@RETURN_VALUE = Finished running [dbo].[insertlogin]. ***************************************************************all i am trying to do is :  creating a SP in VS using managed code and then trying to execute it. But every time i get the above error. If you can tell me how to edit connection string in this that would be very helpful. At present i am using :   Using conn As New SqlConnection("context connection=true") I tried to do "" ALTER ASSEMBLY SqlServerProject1 WITH PERMISSION_SET=EXTERNAL_ACCESS""but i get this error  ""  Msg 10327, Level 14, State 1, Line 1ALTER ASSEMBLY for assembly 'SqlServerProject1' failed because assembly 'SqlServerProject1' is not authorized for PERMISSION_SET = EXTERNAL_ACCESS.  The assembly is authorized when either of the following is true: the database owner (DBO) has EXTERNAL ACCESS ASSEMBLY permission and the database has the TRUSTWORTHY database property on; or the assembly is signed with a certificate or an asymmetric key that has a corresponding login with EXTERNAL ACCESS ASSEMBLY permission. If you have restored or attached this database, make sure the database owner is mapped to the correct login on this server. If not, use sp_changedbowner to fix the problem.""" *********************************************************************Plz help 

View 13 Replies View Related

Rowcount And SQLDataReader

Aug 29, 2006

Hi, from what I can find, there isn't a way to get the number of rows returned from a SQLDataReader command. Is this correct? If so, is there a way around this? My SQLDataReader command is as follows:Dim commandInd As New System.Data.OleDb.OleDbDataAdapter(strQueryCombined, connInd)Dim commandSQL As New SqlCommand("GetAssetList2", connStringSQL)Dim resultDS As New Data.DataSet()'// Fill the dataset with valuescommandInd.Fill(resultDS)'// Get the XML values of the dataset to send to SQL server and run a new queryDim strXML As String = resultDS.GetXml()Dim xmlFileList As SqlParameterDim strContainsClause As SqlParameter'// Create and execute the search against SQL ServerconnStringSQL.Open()commandSQL.CommandType = Data.CommandType.StoredProcedurecommandSQL.Parameters.Add("@xmlFileList", Data.SqlDbType.VarChar, 1000).Value = strXMLcommandSQL.Parameters.Add("@strContainsClause", Data.SqlDbType.VarChar, 1000).Value = strContainsConstructDim sqlReaderSource As SqlDataReader = commandSQL.ExecuteReader()results.DataSource = sqlReaderSourceresults.DataBind()connStringSQL.Close()And the stored procedure is such:DROP PROC dbo.GetAssetList2;GOCREATE PROC dbo.GetAssetList2(@xmlFileList varchar(1000),@strContainsClause varchar(1000))ASBEGINSET NOCOUNT ONDECLARE @intDocHandle intEXEC sp_xml_preparedocument @intDocHandle OUTPUT, @xmlFileListSELECT DISTINCTAssetsMaster.AssetMasterUID,SupportedFiles.AssetPath,FROM AssetsMaster, OPENXML (@intDocHandle, '/NewDataSet/Table',2) WITH (FILENAME varchar(256)) AS x,SupportedFilesWHEREAssetsMaster.AssetFileName = x.FILENAMEAND AssetsMaster.Extension = SupportedFiles.Extension UNIONSELECT DISTINCTAssetsMaster.AssetMasterUID,SupportedFiles.AssetPath,FROM AssetsMaster, OPENXML (@intDocHandle, '/NewDataSet/Table',2) WITH (FILENAME varchar(256)) AS x,SupportedFilesWHEREAssetsMaster.AssetFileName <> x.FILENAMEAND CONTAINS ((Description, Keywords), @strContainsClause)AND AssetsMaster.Extension = SupportedFiles.ExtensionORDER BY AssetsMaster.Downloads DESCEXEC sp_xml_removedocument @intDocHandle ENDGOHow can I access the number of rows returned by this stored procedure?Thanks,James

View 3 Replies View Related

No More Data In A SqlDataReader?

Feb 16, 2007

How do I tell when there is no more data to read in a SQLDataReader?
For example, I have an open datareader that I pass into a function that MIGHT still have a valid row in it when it returns from the function. How do I tell?  I can't do a read() because then that current record will go away. I need to be able to tell if there is a current record without doing another read.
TIA,

View 4 Replies View Related

SqlDataReader.GetOrdinal()

Jun 18, 2007

Say I have this SQL query running into an SqlDataReader select TaskName, TaskDescription from tblTasks where TaskID = 5 There are two different ways to get the data out of the reader (maybe more) TaskName.Text = Reader.GetString(0);andTaskName.Text = Reader.GetString(Reader.GetOrdinal("TaskName")); My question is, is there a major difference in terms of efficiency between these two?  The second one is definitely more robuts (in a situation where you are calling a stored procedure, and the stored procedure might change, etc) but the first one has fewer operations. Is the increase in robustness of the second one worth the potential performance hit, if any? Thank you, -Madrak 

View 2 Replies View Related

What Is The Purpose Of Having SqlDataReader Here?

Jul 23, 2007

May I know what is the purpose of having SqlDataReader in Example A? I can see the same output when I tried out both. Should I use Example A or Example B? Currently, I'm using Example B since it is lesser code.Example A Dim objDR As SqlDataReader 'Create Data Reader

LoginConn.Open()
strSQL = "SELECT CountryID, CountryName FROM Country ORDER BY CountryName "
cmd = New SqlCommand(strSQL, LoginConn) objDR = cmd.ExecuteReader() 'Populate the DataReader ddlNationality.DataSource = objDR ddlNationality.DataBind() ddlNationality.SelectedValue = dvUserProfile.Item(0)("Nationality")LoginConn.Close()  Example BLoginConn.Open() strSQL = "SELECT CountryID, CountryName FROM Country ORDER BY CountryName " cmd = New SqlCommand(strSQL, LoginConn) ddlNationality.DataSource = cmd.ExecuteReader() 'Populate the DataReader ddlNationality.DataBind() ddlNationality.SelectedValue = dvUserProfile.Item(0)("Nationality")LoginConn.Close()

View 2 Replies View Related

Question About SqlDataReader....

Dec 31, 2007

Hello every one and happy new year...
i have a problem with SqlDataReader used in asp.net application:
I defined a public object of SqlDataReader and assigned it the resultset of a query,
well, this happened ,lets say in page 1# but whan i want to use this datareader in another page
it keeps telling my that the reader is closed so i can't abstract information from, regarding that i used it's methods such "Read()" and "NextResult()"
but there is no use, what should i do, help me please  !!!!!?

View 1 Replies View Related

SQLDataReader Problem

Jan 4, 2008

Hello im fairly new to ASP.Net and have a problem with an Intranet Page I am creating. In this part of the page I want to retrive a value from an SQL Table based on criteria and then store it as a variable to be used elsewhere on my page. I have tried using the SQL Data reader to retrive the value but somewhere in my code I am going wrong. Can anyone advise me on this please? See code below
 My Visual Studio debugger has point out that there is a problem with my r = cmd.ExecuteReader() line
 Oh and the connection to my SQL database is opened further up the page from this code.
Dim strSQL As String = "SELECT top 1 OrderID FROM tblStationeryOrder WHERE ORDERMADEBY = '" & lstUsers.SelectedValue & "' ORDER BY OrderID DESC"Dim cmd As New System.Data.SqlClient.SqlCommand
cmd.CommandText = strSQLDim r As System.Data.SqlClient.SqlDataReader
r = cmd.ExecuteReader()Do While r.Read()
Dim OrderID As Integer = r!OrderID
Exit Do
 
 

View 4 Replies View Related

SqlDataReader Problems

Apr 25, 2008

I found this tutorial at C# Station called "Reading Data with the SqlDataReader". 
In my code behind file I followed what I think the tutorial was telling me to do but I keep getting a syntax error near '='



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: Line 1: Incorrect syntax near '='. (Line 45:                     rdr = cmd.ExecuteReader();)
Heres my code:
 
     protected void Page_Load(object sender, EventArgs e)    {        this.lblDate.Text = DateTime.Today.ToString("d");        string username;        username = Convert.ToString(Session["usr"]);        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["csSecurity"].ConnectionString);        SqlDataReader rdr = null;         SqlCommand cmd = new SqlCommand("SELECT PROG_OFF FROM Logon_Table WHERE usr = " + username, conn);                         try                {                    conn.Open();                                         rdr = cmd.ExecuteReader();                }
 
 
 
Any suggestions here would be great.  Any links to tutorials you know of would be helpful also. 
 Thanks

View 2 Replies View Related

SQLdataReader Getting Closed

Jun 7, 2008

I have an sp, which has 2 select statements, so iam using a sqldatareader and binding the data to a dropdown.
the first binding is fine, but when i say dataReader.NextResult(), It is null.It says the reader is closed. Can any one tell a work around for this.
 
thanx in advance,
Anil Kumar.

View 6 Replies View Related

I Have Problem!! About SqlDataReader

Jun 10, 2008

see ths code. please
== DAL ==
        public static SqlDataReader ExecuteReader(SqlParameter param, string sp)        {            using (conn = new SqlConnection(connectString))            {                SqlDataReader sdr = null;                try                {                    conn.Open();
                    comm = new SqlCommand();                    comm.CommandText = sp;                    comm.CommandType = CommandType.StoredProcedure;                    comm.Connection = conn;                    comm.Parameters.Add(param);                    sdr = comm.ExecuteReader(CommandBehavior.CloseConnection);                }                catch(SqlException e)                {                    WriteToLog(e.Message);                }                return sdr;            }        }
and, call above ExecuteReader() flowing this,
 
== BL ==
        public UserEntity GetUserInformation(string UID, string sp)        {            UserEntity ue = new UserEntity();
            SqlParameter userUID = new SqlParameter("@USR_ID", SqlDbType.VarChar, 20);            userUID.Value = UID;
            using (SqlDataReader sdr = DbHelper.ExecuteReader(userUID, "SP_GETUSERINFORMATION"))            {                if (sdr != null)                {                    while (sdr.Read())                    {                        ue.UserId = sdr["lecture_usr_id"].ToString();                        ue.UserName = sdr["lecture_usr_realname"].ToString();                        ue.Email = sdr["lecture_usr_email"].ToString();                        ue.Phone = sdr["lecture_usr_phone"].ToString();                        ue.Lastlogin = (DateTime)sdr["lecture_usr_lastlogin"];                        ue.SignDate = (DateTime)sdr["lecture_usr_signdate"];                    }                }                return ue;            }        }
 
error message is,
Invalid attempt to call Read when reader is closed.
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.InvalidOperationException: Invalid attempt to call Read when reader is closed.Source Error:



Line 77: if (sdr != null)
Line 78: {
Line 79: while (sdr.Read())
Line 80: {
Line 81: ue.UserId = sdr["lecture_usr_id"].ToString();Source File: C:Users
aphyrDocumentsVisual Studio 2008ProjectslectureBusinessLogicUserManager.cs    Line: 77  
 I can't understand!!! I try to debuging!!! but, I don't know.
please help me! 

View 2 Replies View Related

Question About SqlDataReader

Jun 14, 2008

suppose I have a data reader which is returned by excuting a command "SELECT [xxx], [yyy], FROM [zzz]" , then I reads the data as normal. while I am reading , there is another thread that excute an insert command to that table , does this insertion effect the order of data that I am reading?

View 5 Replies View Related

SqlDataReader And Tinyint

Apr 17, 2005

I have an SP that returns a result set that contains a tinyint.  My problem is that, when I try and access this value using GetInt16 (or 32), I get an error saying that "Specified cast is not valid".  TinyInt is 1 byte, or 8 bits.  GetInt16 'Gets the value of the specified column as a 16-bit unsigned integer'.  I am assuming that this is the root cause of my problem.  But, there doesn't seem to be a GetInt8 ?!  Any ideas?
Thanks, Martin

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved