Problems With : SqlDataReader = Command.ExecuteReader()
Apr 11, 2007
I am currently tryinh to have this variable declared :
Dim SQLLecteur As SqlDataReader = Command.ExecuteReader()
And receiving the following error : 'ExecuteReader' is not member of 'String'.
1. The ExecuteReader was not present in the list following the Command.
2. The variable is declared from a : Public Shared Sub
3. This sub is located in a code library referenced in the web.config as a namespace : <add namespace="PAX20070409" />
4. If used directly in the .vb file within this sub : Protected Sub btnConnection_Click, I am not receiving any errors about the Dim.
It is pretty clear why the code is not working, but I have not been able to find a way to fix the problem. I am currently trying to find a way to make the Dim work from within my code library. If you have any idea on how this could be achieve, it would be greatly apreciated.
Thank you :)
RV3
View 4 Replies
ADVERTISEMENT
Jan 18, 2008
HI I am having problem with my Execute Reader. I am trying to insert values from 2 different tables into another table. SqlCommand comm2; SqlDataReader reader2; /* Grabs the stuff out of the database */
comm2 = new SqlCommand("SELECT HiraganaCharacter,HiraganaImage FROM Hiragana", getConnection()); /* opens the database */
comm2.Connection.Open();
/* starts the reader */
reader2 = comm2.ExecuteReader();
/* goes through the first array list */
for (int i = 0; i < checkedLetters.Count; i++) { /* find the data by using the array list value as a where clause */ comm2.CommandText = "SELECT HiraganaCharacter,HiraganaImage FROM Hiragana WHERE HiraganaCharacter ='"
+ checkedLetters[i] + "'"; /* reads through the data */ reader2.Read(); /* puts the ID- this id was set somewhere else */ CommQuickLinksItems.Parameters["@QuickLinkID"].Value = QuickLinkId; CommQuickLinksItems.Parameters["@CharacterName"].Value = reader2["HiraganaCharacter"].ToString(); CommQuickLinksItems.Parameters["@CharacterImagePath"].Value = reader2["HiraganaImage"].ToString(); CommQuickLinksItems.ExecuteNonQuery(); } for (int j = 0; j < checkedLettersKata.Count; j++) { comm2.CommandText = "SELECT KatakanaCharacter,KatakanaImage FROM Katakana WHERE KatakanaCharacter ='"
+ checkedLettersKata[j] + "'"; reader2.Read(); CommQuickLinksItems.Parameters["@QuickLinkID"].Value = QuickLinkId; /* line it dies on */ CommQuickLinksItems.Parameters["@CharacterName"].Value = reader2["KatakanaCharacter"].ToString(); CommQuickLinksItems.Parameters["@CharacterImagePath"].Value = reader2["KatakanaImage"].ToString(); CommQuickLinksItems.ExecuteNonQuery(); } CommQuickLinksItems.Connection.Dispose(); CommQuickLinksItems.Dispose(); comm2.Connection.Dispose(); comm2.Dispose(); My first question is there a better way to setup a SqlCommand to just get the connection and wait on the Command object text? Right now I am doing comm2 = new SqlCommand("SELECT HiraganaCharacter,HiraganaImage FROM Hiragana", getConnection());Which is kinda pointless since in the for loop I change the command to something different right away. At the same time though I don't really want to make a new SqlCommand object in the for loop since then everytime it goes through the loop it would then re grab the connection what I find pointless tooNow the problem How I have it right now it does not grab the right stuff. The first for loop works great and everything gets inserted. The next loop does not work It seems like it it trying to take the data from the first for loop and insert that stuff again since I get this error System.IndexOutOfRangeException was unhandled by user code Message="KatakanaCharacter" Source="System.Data" StackTrace: at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName) at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name) at System.Data.SqlClient.SqlDataReader.get_Item(String name) at Practice.QuickLinks() in g:WebsiteJapanesePractice.aspx.cs:line 385 at Practice.btnQuickLink_Click(Object sender, EventArgs e) in g:WebsiteJapanesePractice.aspx.cs:line 411 at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException: Basically what I did was for the first loop I chose 2 items and for the 2nd loop I chose 3 items. When it died on this line CommQuickLinksItems.Parameters["@CharacterName"].Value = reader2["KatakanaCharacter"].ToString();The value was "i" but that was one of the values I choose for the first for loop. It should have been either u,e,o. So I am not sure what I am doing wrong. I thought as long as I change the Command text I would not need to do anything else but it seems like I am missing something.
View 5 Replies
View Related
Nov 26, 2006
Code:
connstr = "my connction info"
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open connstr
Set objCmd=Server.CreateObject("ADODB.Command")
set objCmd.ActiveConnection = objconn
objCmd.CommandText = "my stored procedure"
objCmd.CommandType = 4
objcmd.parameters.append objcmd.createparameter("@itemcheckduplicate", 200, 1, 30, itemadd)
SqlDataReader forduplicate = objcmd.ExecuteReader()
my procedure :
@itemcheckduplicate varchar(30)
as
select sw_item_itemid
from sw_item
where sw_item_item like @itemcheckduplicate
why my command doesnt support ExecuteReader ?
Microsoft VBScript runtime error '800a01b6'
Object doesn't support this property or method: 'ExecuteReader'
View 2 Replies
View Related
Mar 3, 2008
Hi.
I'm trying to read data from a database. This is my code:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
connection.Open();SqlCommand cmd = new SqlCommand(sql, connection);
myReader = cmd.ExecuteReader();if (myReader.Read())
{
name1TextBox.Text = myReader.GetString(1);
addr1TextBox.Text = myReader.GetString(2);
code1TextBox.Text = myReader.GetString(5);
tel1TextBox.Text = myReader.GetString(6);
fax1TextBox.Text = myReader.GetString(7);
:
:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
The above code works fine until one of the GetString calls trys to return NULL (in this case myReader.GetString(5)).
In other words, this code will run through about 30 rows of data until it runs in to a NULL entry for one of the columns.
At that stage it's too late. I'm not allowed call GetString( ) on a NULL value.
Is there anyway I can test the column entry before calling GetString( ).
Regards (& thanks in advance)
Garrett
View 4 Replies
View Related
Nov 14, 2007
when I execute the line:
reader = comm.ExecuteReader();
Is there a way to get a count of the number of records returned (the query is a SELECT with no count in it)? I want to vary the display of the results set based on the number of records returned.
For example if no records are returned I want it to display nothing, if one, I want the header to be in the singular, but if more than one record is returned, I want it to display the header in plural form.
Here is my code snippet with further explanation of what I am trying to do:int Inumber = 0;foreach (string item in menuHeaders)
{string title = menuHeaders[Inumber];
sp.Value = menuHeaders[Inumber];
Inumber++;
conn.Open();reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
//Get the culture property of the thread.CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
//Create TextInfo object.TextInfo textInfo = cultureInfo.TextInfo;
// WHAT I AM TRYING TO DO....... Here I would like to wrap this with an if statement, if Records returned by the reader are 0, skip while loop and header display
// If one, then display in singular and if 2 add an s to the title. Convert to title case and display.content.Text += "<H3>" + textInfo.ToTitleCase(title) + "</H3>";while (reader.Read())
{
content.Text += "<a href='" + reader["website"] + "'>" + reader["f_name"] + reader["l_name"] + "</a>"+ ", " +reader["organization"]+"<br />";
}
//Close the connection.
reader.Close();
conn.Close();
}
View 1 Replies
View Related
Jan 28, 2008
Hi all,I have a script which I am running to get the minimum date from a database table.I've connected to the database and run the sql but when I try to get the result i get an error saying "No data exists for the row/column."This is the code I have for it at the moment.1 Dim mySql As String = "SELECT MIN(LOSS_DATE) AS minDate FROM dbo_CLAIMS"
2 Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|NexusHolding.mdb;Persist Security Info=True"
3 Dim dbCon As New OleDbConnection(connectionString)4
5 dbCon.Open()6
7 Dim dbComm As New OleDbCommand(mySql, dbCon)8 Dim dbRead = dbComm.ExecuteReader()9 Dim minDate As String = dbRead.GetValue(0)10
11 Response.Write(minDate)Thanks in advance for any help.
View 3 Replies
View Related
Feb 27, 2004
Hi. I am executing a stored procedure. The stored procedure raises an error and all I need is to catch this error. Pretty simple, but it only works with an ExecuteNonQuery and not with an Executereader statement. Can anybody explain to me why this happens?
Here's the sp:
CREATE PROCEDURE dbo.rel_test
AS
select 1
raiserror ('My error.', 11, 2)
return
GO
Here's the ASP.Net page:
<% @Page Language="VB" debug="True" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script runat="server">
Public Function RunSP(ByVal strSP As String) As SqlDataReader
Dim o_conn as SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
AddHandler o_conn.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)
o_conn.Open
Dim cmd As New SqlCommand(strSP, o_conn)
cmd.CommandType = System.Data.CommandType.StoredProcedure
Dim rdr as SqlDataReader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
rdr.Close()
cmd.Dispose()
Response.Write(o_conn.State)
End Function
Private Sub OnInfoMessage(sender as Object, args as SqlInfoMessageEventArgs)
Dim err As SqlError
For Each err In args.Errors
Response.Write(String.Format("The {0} has received a severity {1}, state {2} error number {3}" & _
"on line {4} of procedure {5} on server {6}:{7}", _
err.Source, err.Class, err.State, err.Number, err.LineNumber, _
err.Procedure, err.Server, err.Message))
Next
End Sub
Sub Page_Load(sender as Object, e as EventArgs)
RunSP("rel_test")
End Sub
</script>
View 2 Replies
View Related
Jul 5, 2005
I am not seeing why this is not executing the reader, it just goes right by it when stepping through the code...
command.CommandType = CommandType.StoredProcedure;
// course
command.Parameters.Add( "@courseId", courseId );
// Parameter: LessonName
SqlParameter sLessonName = command.Parameters.Add( "@lessonName", SqlDbType.VarChar );
sLessonName.Size = 256;
sLessonName.Direction = ParameterDirection.Output;
// error code
SqlParameter pErrCode = command.Parameters.Add( "@errCode", SqlDbType.Int );
pErrCode.Direction = ParameterDirection.Output;
// execute the stored procedure
SqlDataReader spResults;
conn.Open();
spResults = command.ExecuteReader();
while( spResults.Read() ) // It never steps into the while statement like the reader is completed
{
RetrieveObjId objNames = new RetrieveObjId( spResults.GetString( 0 ));
searchResults.Add( objNames );
}
spResults.Close();And the stored procedure is.....CREATE PROCEDURE dbo.retrieveLessonNames @courseId VARCHAR(20), @lessonName VARCHAR(256) OUTPUT, @errCode INT OUTPUT ASBEGIN
SELECT @lessonName = objName FROM objStructure WHERE courseId = @courseId
SET @errCode = 0 RETURN @errCode HANDLE_APPERR: SET @errCode = 1 RETURNHANDLE_DBERR: SET @errCode = -1 RETURNENDGOSuggestions?Thanks all,Zath
View 3 Replies
View Related
Oct 26, 2006
I have VS 2005 and SQL CE 3.0. I sometimes get the a FileNotFoundException when I first use ExecuteReader. I believe this is because a dll has not been copied across because if I restart the emulator I can get it to work again.
Do I need to add a cab file/dll to my project to stop this happening?
Thanks
Emmet
View 1 Replies
View Related
Apr 23, 2008
I'm writing my first vb.net app. Have a default page that uses a persons network login to query a database to get all their timekeeper id, firstname, last name, etc. But I keep getting this error. (My code is below) What am I missing???
ExecuteReader: Connection property has not been initialized.
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: ExecuteReader: Connection property has not been initialized.Source Error:
Line 21: conn.Open()
Line 22:
Line 23: reader = comm.ExecuteReader()
Line 24: If reader.Read() Then
Line 25: EmployeesLabel.Text = reader.Item("tkinit")
<script runat="server">Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)Dim conn As SqlConnectionDim comm As SqlCommandDim reader As SqlDataReaderDim connectionString As String = ConfigurationManager.ConnectionStrings("xxxConnectionString").ConnectionStringcomm = New SqlCommand("Select top 1 tkinit, tklast, tkfirst +' '+ tklast as fullname from txxx WHERE login = @login)", conn)comm.Parameters.Add("@Login", Data.SqlDbType.VarChar)comm.Parameters("@Login").Value = Me.User.Identity.Name.Substring(User.Identity.Name.IndexOf("") + 1)conn = New SqlConnection(connectionString)conn.Open()reader = comm.ExecuteReader()If reader.Read() ThenEmployeesLabel.Text = reader.Item("tkinit")FirstLastName.Text = reader.Item("fullname")End Ifreader.Close()conn.Close()End Sub</script>
View 1 Replies
View Related
Mar 11, 2005
I have a web form that is generating an error and I can't seem to figure out why for the life of me. Below is the code:
Private Sub VerifyNoDuplicateEmail()
Dim conn As SqlConnection
Dim sql As String
Dim cmd As SqlCommand
Dim id As Guid
sql = "Select UserID from SDCUsers where email='{0}'"
sql = String.Format(sql, txtEmail.Text)
cmd = New SqlCommand(sql, conn)
conn = New SqlConnection(ConfigurationSettings.AppSettings("cnSDCADC.ConnectionString"))
conn.Open()
Try
'The first this we need to do here is query the database and verify
'that no one has registed with this particular e-mail address
id = cmd.ExecuteScalar()
Response.Write(id.ToString & "<BR>")
Catch
Response.Write(sql & "<BR>")
Response.Write("An error has occurred: " & Err.Description)
Finally
If Not id.ToString Is Nothing Then
'The e-mail address is already registered.
Response.Write("Your e-mail address has already been registered with this site.<BR>")
conn.Close()
_NoDuplicates = False
Else
'It's safe to add the user to the database
conn.Close()
_NoDuplicates = True
End If
End Try
End Sub
Web.Config
<appSettings>
<!-- User application and configured property settings go here.-->
<!-- Example: <add key="settingName" value="settingValue"/> -->
<add key="cnSDCADC.ConnectionString" value="workstation id=STEPHEN;packet size=4096;integrated security=SSPI;data source=SDCADC;persist security info=False;initial catalog=sdc" />
</appSettings>
Can anyone show me the error of my ways?
Thanks,
Stephen
View 4 Replies
View Related
Oct 2, 2007
Hello All,
I receive the following error when attempting to preview or run a simple report:
ExecuteReader: CommandText propert has not been initialized
I have searched the help website and other forums, but I have had no success.
I am new to Reporting Services and this is one of the first reports I have created. All of my reports have this error.
Any ideas?
Thanks in advance.
View 1 Replies
View Related
Sep 24, 2007
Hello and thanks in advance.
This error was received executing a SqlCeCommand method of ExecuteReader();
I have only found 3 hits in Google about this error and the time it was asked in a MS forum it was not answered. I need an answer, please.
bombar...see code below
SqlCeDataAdapter adp = null;
adp = new SqlCeDataAdapter();
SqlCeCommand cmd;
cmd = _Con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into InventoryCounts(DateTime,WarehouseID,PartID,LotID,UserName,Count) VALUES(?,?,?,?,?,?)";
adp.InsertCommand = cmd;
cmd = _Con.CreateCommand();
cmd.Parameters.Clear();
SqlCeParameter p1 = cmd.Parameters.Add("DateTime",SqlDbType.DateTime);
SqlCeParameter p2 = cmd.Parameters.Add("WarehouseID",SqlDbType.NChar,20);
SqlCeParameter p3 = cmd.Parameters.Add("PartID", SqlDbType.NChar,20);
SqlCeParameter p4 = cmd.Parameters.Add("LotID", SqlDbType.NChar,20);
SqlCeParameter p5 = cmd.Parameters.Add("UserName", SqlDbType.NChar,20);
SqlCeParameter p6 = cmd.Parameters.Add("Count", SqlDbType.Int);
p1.Value = Convert.ToString(DateTime.Now);
p2.Value = "Warehouse1";
p3.Value = txtBPartIDShow.Text;
p4.Value = txtBLotIDEntry.Text;
p5.Value = "JHB";
p6.Value = Convert.ToInt32(txtBCountEntry.Text);
cmd = _Con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into InventoryCounts(DateTime,WarehouseID,PartID,LotID,UserName,Count) VALUES(?,?,?,?,?,?)";
cmd.Prepare();
cmd.ExecuteReader();
View 4 Replies
View Related
Jan 29, 2008
Hi,
I have written a CLR Function in C#. The function works as expected except that I am trying to read data some data during the function call and get the following error:
Msg 6522, Level 16, State 1, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "fn_SLARemaining":
System.InvalidOperationException: ExecuteReader: Connection property has not been initialized.
System.InvalidOperationException:
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader()
at SLARemaining.SupportTimes.addSupportHours()
at SLARemaining.CalculateTimeRemaining.GetTimeRemaining(String openDate, Decimal SLADuration)
at UserDefinedFunctions.fn_SLARemaining(SqlDateTime DateFrom, SqlDateTime DateTo, SqlInt32 PriorityTime, SqlDecimal AdjustmentTime, SqlDecimal Status)
.
The main code for the function is this:
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static SqlString fn_SLARemaining(SqlDateTime @DateFrom, SqlDateTime @DateTo, SqlInt32 @PriorityTime, SqlDecimal @AdjustmentTime, SqlDecimal @Status)
{
SLARemaining.CalculateTimeRemaining remaining;
remaining = new SLARemaining.CalculateTimeRemaining();
int duration = Convert.ToInt32(PriorityTime.ToString());
if (!DateFrom.IsNull)
{
string date = DateFrom.Value.ToShortDateString() + " " + DateFrom.Value.ToShortTimeString();
SqlString result = remaining.GetTimeRemaining(date, duration);
return result;
}
else
{
return null;
}
}
};
The function calls the following method from another class:
public string[] addSupportHours()
{
string[] supportedHours = new string[28];
SqlDataReader dr;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "xxxxxxx"; //<-- commented out for this post
using (SqlConnection cn = new SqlConnection("context connection=true;"))
{
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
//do some stuff
}
cn.Close();
cn.Dispose();
}
The error message claims that the connection has not been initialized - can't work out why? Any help will be appreciated!
View 3 Replies
View Related
Apr 26, 2007
I am accessing SQL2005 with C# code using OleDbConnection.
A try and catch block catches the following error once a while between the Open() and Close() of the connection:
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
I do not even have any idea where to start to debug this. The ExecuteNonQuery() runs a delete SQL query. It works 99.9% of the time. I do not see anything wrong when this error happens.
Any hint would be greatly appreciated.
View 9 Replies
View Related
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Jan 29, 2006
hi..i am kind of new to asp.net n having trouble with the SqlException error message.. n this code works as 1st page pass the id to second page and the second page took the id to execute the query..i dun know the wer the error occurs..can give a help..Thanks.
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection connection = null;
SqlCommand command = null;
string sqlConnection = null;
string sql = null;
string ab = null;
sqlConnection = ConfigurationSettings.AppSettings["MSQLConnectionString"];
connection = new SqlConnection(sqlConnection);
if (!Page.IsPostBack)
{
try
{
if (Request.QueryString["categoryID"] == null)
{
}
else
{
ab= Request.QueryString["categoryID"].ToString(); //getting the id from page that pass this values
sql = "Select groupname, categoryid, description from groups where groups.categoryid=?"; // can this query execute?
command = new SqlCommand(sql, connection);
connection.Open();
command.Parameters.Add(new SqlParameter("categoryid", ab));
reader = command.ExecuteReader(); // error on here "SqlException"
while (reader.Read())
{
group.InnerText = reader["groupname"].ToString();
desc.InnerText = reader["description"].ToString();
}
}
}
finally
{
if (reader != null)
{
reader.Close();
}
if (connection != null)
{
connection.Close();
}
}
}
View 1 Replies
View Related
Feb 23, 2007
i am using visual web developer 2005 and SQL 2005 with VB as the code behindi am using INSERT command like this Dim test As New SqlDataSource() test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString1").ToString() test.InsertCommandType = SqlDataSourceCommandType.Text test.InsertCommand = "INSERT INTO try (roll,name, age, email) VALUES (@roll,@name, @age, @email) " test.InsertParameters.Add("roll", TextBox1.Text) test.InsertParameters.Add("name", TextBox2.Text) test.InsertParameters.Add("age", TextBox3.Text) test.InsertParameters.Add("email", TextBox4.Text) test.Insert() i am using UPDATE command like this Dim test As New SqlDataSource() test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ToString() test.UpdateCommandType = SqlDataSourceCommandType.Text test.UpdateCommand = "UPDATE try SET name = '" + myname + "' , age = '" + myage + "' , email = '" + myemail + "' WHERE roll 123 " test.Update()but i have to use the SELECT command like this which is completely different from INSERT and UPDATE commands Dim tblData As New Data.DataTable() Dim conn As New Data.SqlClient.SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True") Dim Command As New Data.SqlClient.SqlCommand("SELECT * FROM try WHERE age = '100' ", conn) Dim da As New Data.SqlClient.SqlDataAdapter(Command) da.Fill(tblData) conn.Close() TextBox4.Text = tblData.Rows(1).Item("name").ToString() TextBox5.Text = tblData.Rows(1).Item("age").ToString() TextBox6.Text = tblData.Rows(1).Item("email").ToString() for INSERT and UPDATE commands defining the command,commandtype and connectionstring is samebut for the SELECT command it is completely different. why ?can i define the command,commandtype and connectionstring for SELECT command similar to INSERT and UPDATE ?if its possible how to do ?please help me
View 2 Replies
View Related
Feb 13, 2007
My query is as follows:Dim CurrentDate As DateCurrentDate = "09/02/2007" MyCommand = New SqlCommand("SELECT RegisterID FROM Registers WHERE RegisterDate = @RegisterDate AND IsMorningRegister = 1", MyConn)MyCommand.Parameters.Add("@RegisterDate", Data.SqlDbType.DateTime)MyCommand.Parameters("@RegisterDate").Value = CurrentDate My DB table is called RegisterDate and is of type DateTime. The record that should be matched is: Register ID: 13 RegisterDate: 09/02/2007 09:00:00IsMorningRegister: TrueIsAfternoonRegister: False But no records are returned. Any idea why?
View 4 Replies
View Related