SqlException Error

 hi there

i've copied my code below. I've checked my database and everything is fine. I'm not very sure about the error stated below.
Can anyone help?
Thank u very much!

 

View Replies


ADVERTISEMENT

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

SqlException - Error Expects Parameter HostID; Which Was Not Supplied

Why am I getting this error, what does it mean and how can I fix it. Here is my stored proceduce and method to call it.
ALTER PROCEDURE dbo.hnDeleteHost(@pHostID varchar(50), @pRet int out)AS
SELECT Host FROM HostName WHERE HostNameID = @pHostID
if (@@ROWCOUNT > 0) begin DELETE FROM HostName WHERE HostNameID = @pHostID SET @pRet = @@ROWCOUNTendelse begin SET @pRet = -1end
 And the method
using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]))            {
                cn.Open();                SqlCommand cmd = new SqlCommand("hnDeleteHost", cn);                cmd.CommandType = CommandType.StoredProcedure;                cmd.Parameters.Add(new SqlParameter("@pHostID", SqlDbType.VarChar, 50, "HostNameID"));                cmd.UpdatedRowSource = UpdateRowSource.None;                cmd.ExecuteNonQuery();            }

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: 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

Error: System.Data.SqlClient.SqlException: Timeout Expired.

Hi,
    I am getting an time out expired error while import dbf files to the database.. In this upload one file had 379 records.. and it inserts it into the few tables and then i get the above error..in my event viewer.
 Error: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
No Changes made to the Plan table.
Inserting records(s) in Plan table.
No Changes made to Plan table.
Updating changes to PlanStatementInfo.
Updated 1 record(s) in PlanStatementInfo.
Inserting new records into PlanStatementInfo.
No new records were added to PlanStatementInfo.
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.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(SqlConnection connection, CommandType commandType, String commandText, SqlParameter[] commandParameters)
at Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(String connectionString, CommandType commandType, String commandText, SqlParameter[] commandParameters)
at Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(String connectionString, String spName, Object[] parameterValues)
at icc.BaseClasses.DL.DLImportPlan.Import(Int32 ClientId, Int32 PeriodId, Int32 UserId) in C:Documents and SettingsMy DocumentsPlanStatementsImportDLDLImportPlan.cs:line 116

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.cs:line 116 --this is where i am calling my sproc...  
 any help will will appreciated
Thanks,
Karen

View Replies View Related

2tier And Asp.net Sql Error : [SqlException: SQL Server Does Not Exist Or Access Denied.]

Dear all,

I developed an asp.net application by using .net frame work 1.1 and sql server 2000.
i was using 2 tier arch (database server is different and web server is different).
my problem is ,connection to sql server is not stable,some times it works and some times
it raises error that sql server does not exist or access denied.please help me to solve this problem

View Replies View Related

Java.sql.SQLException: I/O Error: SSO Failed: Native SSPI Library Not Loaded.

Hi,

I tried to connect to SQLServer from a java application using jTDS driver jars, with Windows authentication. The following error is thrown,

java.sql.SQLException: I/O Error: SSO Failed: Native SSPI library not loaded. Check the java.library.path system property.


From the above error i realised that the ntlmauth.dll is to be loaded to path. I compiled and run the application as follows,

java -Djava.library.path=<dll_lib_path>

still i get the same error,

any suggestions to overcome this error.

regards,
Shefu

View Replies View Related

System.Data.SqlClient.SqlException: An Error Has Occurred While Establishing A Connection To The Server.

Is it possible to connect to an Access database on my local drive, or does it have to an SQL database? Here is the error I am getting: 
Server Error in ' 'Application.


An error has occurred while establishing a connection to the server.
 When connecting to SQL Server 2005, this failure may be caused by the fact that
under the default settings SQL Server does not allow remote connections.
(provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance
Specified) 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 error has occurred while establishing
a connection to the server.  When connecting to SQL Server 2005, this failure
may be caused by the fact that under the default settings SQL Server does not
allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error
Locating Server/Instance Specified)Source Error:



Line 19: Dim ConString As String = ("Data Source=C:Inetpubwwwrootmessage.mdb")Line 20: Dim myDataAdapter As New SqlDataAdapter(SQLStatement.Text, ConString)Line 21: myDataAdapter.Fill(myDataSet, "tblMessage")Line 22: myDataGrid.DataSource = myDataSet.Tables("tblMessage")Line 23: myDataGrid.DataBind()

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

SqlException

Hello,
I am having trouble catching an sqlexception. When i try to put data into my database that is duplicate i want it to display an error message and so catch the exception however i am getting errors. The catch statement i am using is:Label lab1 = (Label)FormView1.FindControl("Label10");
try
{
EditSqlDataSource.Insert();Response.Redirect("Appointments.aspx");
}catch (Exception ex)
{lab1.Text = "Appointment Slot Already Taken: Booking Not Made.";
}
and the error that i am getting is:
Error 1 The type or namespace name 'SqlException' could not be found (are you missing a using directive or an assembly reference?) 
Thanks in advance Mike

View Replies View Related

Odd SqlException

I'm using .NET 2.0
I designed my BLL to work as follows:  'Update existing company
<System.ComponentModel.DataObjectMethodAttribute _
(System.ComponentModel.DataObjectMethodType.Update, True)> _
Public Function UpdateCompany(ByVal Original_CompanyID As Int64, ...) As Boolean

'Get current record
Dim Companies As biodata.CompaniesDataTable = CompaniesAdapter.GetCompanyByID(Original_CompanyID)

'If no record exists, Update fails
If Companies.Count = 0 Then
Throw New ApplicationException("Company does not exist.")
End If

Dim Company As biodata.CompaniesRow = Companies(0)

'Set all the values to load into the database
Company.CompanyName = CompanyName
...

Dim RowsAffected As Integer = CompaniesAdapter.Update(Company)
Return (RowsAffected = 1)
End Function
 Recently I deleted a column in my SQL database.  In order to account for this change, I deleted the same column in my DAL.  Then, because of the obvious compile errors that would occur if I didn't, I deleted all references to that column in my BLL.  My DAL automatically creates the Update and Insert statements.  Now, the error I'm getting is as follows:
Exception Details: System.Data.SqlClient.SqlException: Cursorfetch: The number of variables declared in the INTO list must match that of selected columns.The statement has been terminated.Source Error:



Line 18409: System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Line 18410: Public Overloads Overridable Function Update(ByVal dataRow As System.Data.DataRow) As Integer
Line 18411: Return Me.Adapter.Update(New System.Data.DataRow() {dataRow})
Line 18412: End Function
Line 18413:
Stack Trace:



[SqlException (0x80131904): Cursorfetch: The number of variables declared in the INTO list must match that of selected columns.
The statement has been terminated.]
System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount) +200
System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount) +104
System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping) +3042
System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows) +345
biodataTableAdapters.CompaniesTableAdapter.Update(DataRow dataRow) in C:WINDOWSMicrosoft.NETFrameworkv2.0.50727Temporary ASP.NET Files
oot67b7db20aea00f88App_Code.nf1apfb7.1.vb:18411
CompaniesBLL.UpdateCompany(Int64 Original_CompanyID, String CompanyName, String Division, String Website, Nullable`1 CompanyInactive, String CompanyInactiveReason, Nullable`1 EmployeeCount, Nullable`1 YearFounded, Nullable`1 YearStartedBiobased, Nullable`1 NAICS, String Address1, String Address2, String City, String StateCode, String Territory, String CountryCode, String Zip, String CompanyNotes, String Prefix, String FName, String LName, String Suffix, String Title, String Email, String Phone1, String PhoneType1, String Phone2, String PhoneType2, String Phone3, String PhoneType3, String UpdateType, String UpdatedBy, Int64 SecurityLevel, Int64[] Flags) in F:App_CodeBLLCompaniesBLL.vb:376

Now, this exception makes no sense to me because the DAL should automatically fix the update and insert statements itself, and I never directly access those statements.  The error is occuring at CompaniesAdapter.Update(Company) in my code above.  Any ideas?
Thanks,BSY E-718

View Replies View Related

SQLException! (again)

I'll try re-posting this, as the other post didn't seem to take.
I'm a long time "classic" ASP developer used to SQL Server 2000.  I'm messing around now with Visual Web Developer 2005 and SQL Server Express 2005 (both latest versions).  I've inclided an MDF file with my ASP.NET project, and have created some tables and entered some data.  From time to time, when starting the site, I receive the following error:

A transport-level error has occurred when sending the request to the server. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.)
It always appears on this line:

Dim retReader As SqlDataReader = MyCommand.ExecuteReader
I've posted this question elsewhere, and haven't received any insight as to what the problem may be.  Can anyone help?
 Thanks;
Brad Brening

View Replies View Related

SqlException

Hi,
Here is my stored procedure and when I'm trying to use it through my code, it throws this SqlException. As it shows @JulianDate is infact a parameter of my SP. What am I doin wrong here??


CREATE PROC CabsSchedule_Save
(
@JulianDatesmallint,
@SiteCodesmallint,
@YearMonthsmallint,
@CalendarDaysmallint,
@BillPeriodsmallint,
@WorkDaysmallint,
@CalDayBillRcvdvarchar(30),
@Remarksvarchar(50)
)
AS
DELETE FROM CabsSchedule WHERE YearMonth = @YearMonth AND SiteCode = @SiteCode;

DECLARE @InsQuery NVARCHAR(2000)
DECLARE @ValInsQuery NVARCHAR(2000)
DECLARE @FullQuery NVARCHAR(4000)

SET @InsQuery = 'INSERT INTO CabsSchedule(JulianDate, SiteCode, YearMonth, CalendarDay, BillPeriod, WorkDay '
SET @ValInsQuery = 'VALUES (@JulianDate, @SiteCode, @YearMonth, @CalendarDay, @BillPeriod, @WorkDay'

IF NOT @CalDayBillRcvd IS NULL
BEGIN
SET @InsQuery = @InsQuery + ', CalDayBillRcvd, '
SET @ValInsQuery = @ValInsQuery + ', @CalDayBillRcvd, '
END

IF NOT @CalDayBillRcvd IS NULL
BEGIN
SET @InsQuery = @InsQuery + ', Remarks'
SET @ValInsQuery = @ValInsQuery + ', @Remarks'
END

BEGIN
SET @ValInsQuery = @ValInsQuery + ')'
SET @FullQuery = @InsQuery + @ValInsQuery
END
GO



Error Details
@JulianDate smallint, is not a parameter for procedure CabsSchedule_Save.
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: @JulianDate smallint, is not a parameter for procedure CabsSchedule_Save

Any help Appreciated.

Thanks,

View Replies View Related

SqlException

I am new to Sql Server 2005, I am using vb.net 2005 to manually connect to the database but I am getting the following error
Login failed for user 'BM-PC/B-Mustafa'

Can you please advise?

Thanks

View Replies View Related

Need Help With SqlException

I have extended a table adapter(the one generated with the VS wizard) for one of my tables so i could add an overload to the Fill method to return rows within a certain datetime range from a smalldatetime collumns in the same table






Code Snippet



[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Fill, true)]
public int Fill(WrkDS.TransferenciasDataTable dataTable, DateTime Data1, DateTime Data2)
{
//Instanciar comando com filtro

string ComandoQuery = "SELECT * FROM Transferencias WHERE Data >= '" + Data1.ToString("yyyyMMdd") + "' and Data <= '" + Data2.ToString("yyyyMMdd") + "'";


SqlCommand ComandoComFiltro = new SqlCommand(ComandoQuery, this._connection);

this.Adapter.SelectCommand = ComandoComFiltro;
if ((this.ClearBeforeFill == true))
{
dataTable.Clear();
}
System.Windows.Forms.MessageBox.Show(ComandoComFiltro.CommandText);
int returnValue = this.Adapter.Fill(dataTable);
return returnValue;
}








as you can see the string "ComandoQuery" is in a valid sql format, in fact I executed the exact same query in SQL server management studio and it returned the rows i wanted but when i try it in my application it trows an SqlException "The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value."


this is really making my head hurt, i cant seem to figure whats wrong, if someone has any clue please post here.

thanks.

View Replies View Related

Need Help With SQlException, Please!

Hi,

I get the following error when I try to run a stored procedure


"Cannot insert explicit value for identity column in table 'CurrentGroup' when IDENTITY_INSERT is set to OFF"

The procedure looks like so...



USE [AdminDB]

GO



SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

ALTER PROCEDURE [dbo].[insert_group]

(

@cgpActivityGroupID nvarchar(30),

@cgpPreRegistredFrom nvarchar(30),

@cgpRegistredFrom nvarchar(30),

@cgpRegistredTo nvarchar(30),

@cgpMaximalNumber nvarchar(30),

@cgpStartDate nvarchar(40)

)

AS

INSERT INTO dbo.CurrentGroup(cgpID, cgpActivityGroupID, cgpPreRegistredFrom, cgpRegistredFrom, cgpRegistredTo, cgpMaximalNumber, cgpStartDate)

VALUES (@@identity, @cgpActivityGroupID, @cgpPreRegistredFrom, @cgpRegistredFrom, @cgpRegistredTo, @cgpMaximalNumber, @cgpStartDate)


Thanks in advance!

View Replies View Related

Problem With SqlException

 
Hi,
 I get an error as I try to insert to SQL server using a stored procedure:
"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."For some reason the stored procedure inserts every row twice. Does anyone know what could be wrong?
 Thanks in advance!string sCN = ConfigurationManager.ConnectionStrings["AdminConnectionString"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(sCN);System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;string strTemp = (Session["activityID"]).ToString();if (strTemp != "")
{
string sql2 = Session["txtFirstName"].ToString();string sql3 = Session["txtLastName"].ToString();
string sql4 = Session["txtStreetAddress"].ToString();string sql6 = Session["txtPostalAddress"].ToString();
string sql7 = Session["txtTelephoneHome"].ToString();
string sql10 = Session["txtEmail"].ToString();
string sql13 = Session["txtAppartmentNo"].ToString();
 cmd.Parameters.AddWithValue("@mbrFirstName", sql2);
cmd.Parameters.AddWithValue("@mbrLastName", sql3);cmd.Parameters.AddWithValue("@mbrStreetAddress", sql4); cmd.Parameters.AddWithValue("@mbrPostalAddress", sql6);
cmd.Parameters.AddWithValue("@mbrTelephoneHome", sql7);
cmd.Parameters.AddWithValue("@mbrEmail", sql10);

Int32 rowsAffected;cmd.CommandText = "insert_member";cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();

View Replies View Related

Problem With SQLException

Hello... 
string query = "insert into Offer_Assignment (Offer_Id,Cust_Id,Assigned_Date) values ("+ds.Tables[0].Rows[i][0]+","+ds.Tables[0].Rows[i][1] + ",convert(DateTime,'"+ds.Tables[0].Rows[i][2]+"'))";
When i excute this query in my system am getting this following error.
"Conversion failed when converting datetime from character string."I am retrieving datetime value form another table And inserting into Offer_Assignment table.Am using Convert method to convert the value am getting from the dataset into datetime.But still am getting this error.
Can you please help me to resolve ths issue.
Thanks.

View Replies View Related

Help SqlException (0x80131904):

Hi, I recently changed a Datatype from varchar to text as I wanted to store more text in my database table. Doing so caused my application to crash as "A severe error occurred on the current command". In theory It shouldn't have caused the application to fall over but it does. Can someone please examine my code below and give me any ideas. I've been looking at this for hours with no luck. I've highlighted where the error occurs in red text. Thanks in advance Source Error:Line 337:try {
Line 338:_SqlConnection.Open();
Line 339:IN_SqlCommand.ExecuteNonQuery();
Line 340:} finally {
Line 341:if (_SqlConnection != null) _SqlConnection.Close();Stack Trace:[SqlException (0x80131904): A severe error occurred on the current command. The results, if any, should be discarded.
A severe error occurred on the current command. The results, if any, should be discarded.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +862234
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +739110
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1956
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +149
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +903
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +415
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135
System.SmartObject.setInfo() in w:wwwdat4121App_Codesmart.cs:339
ASP.admin_index_aspx.TrimDisplayOrder() in w:wwwdat4121adminindex.aspx:170
ASP.admin_index_aspx.Page_Load(Object sender, EventArgs e) in w:wwwdat4121adminindex.aspx:44
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +34
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061 
Source Code: public SqlParameter getParameter (string AR_property) {            for (int i=0;i < _SqlParameters.Length;i++) {                if (string.Compare(_SqlParameters[i].SourceColumn, AR_property, true) == 0) return _SqlParameters[i];            }            return null;        }                                public void getInfo () {            if (Identity > 0) {                SqlCommand IN_SqlCommand = new SqlCommand(String.Format("SELECT * FROM {0} WHERE {1} = {2}", _table, _KeySqlParameter.SourceColumn, _KeySqlParameter.ParameterName), _SqlConnection);                IN_SqlCommand.Parameters.Add(_KeySqlParameter);                            try {                    _SqlConnection.Open();                    SqlDataReader INsqlDataReader = IN_SqlCommand.ExecuteReader(CommandBehavior.SingleRow);                    INsqlDataReader.Read();                                        if (INsqlDataReader.HasRows) {                        for (int i=0;i < _SqlParameters.Length;i++) {                            _SqlParameters[i].Value = INsqlDataReader[_SqlParameters[i].SourceColumn];                        }                        INsqlDataReader.Close();                    }                } finally {                    if (_SqlConnection != null) _SqlConnection.Close();                    IN_SqlCommand.Parameters.Clear();                    IN_SqlCommand.Dispose();                }            }        }                        public virtual void setInfo () {                        for(int i=0;i < _SqlParameters.Length;i++) {                if (_SqlParameters[i].Value == null || _SqlParameters[i].Value.ToString() == String.Empty) {                    if (_SqlParameters[i].IsNullable) {                        _SqlParameters[i].Value = DBNull.Value;                    } else {                        if (_SqlParameters[i].SqlDbType == SqlDbType.VarChar || _SqlParameters[i].SqlDbType == SqlDbType.Text) {                            _SqlParameters[i].Value = String.Empty;                        } else if (_SqlParameters[i].SqlDbType == SqlDbType.SmallDateTime || _SqlParameters[i].SqlDbType == SqlDbType.DateTime) {                            _SqlParameters[i].Value = DateTime.Now;                        } else {                            _SqlParameters[i].Value = 0;                        }                    }                }             }                            if (Identity > 0) {                            System.Text.StringBuilder INstringBuilder = new System.Text.StringBuilder();                INstringBuilder.Append(String.Format("SET NOCOUNT ON;UPDATE {0} SET ", _table));                for(int i=0;i < _SqlParameters.Length;i++) {                    INstringBuilder.Append(_SqlParameters[i].SourceColumn);                    INstringBuilder.Append("=");                    INstringBuilder.Append(_SqlParameters[i].ParameterName);                    if (i+1 != _SqlParameters.Length) INstringBuilder.Append(", ");                }                        INstringBuilder.Append(" WHERE ");                INstringBuilder.Append(_KeySqlParameter.SourceColumn);                INstringBuilder.Append("=");                INstringBuilder.Append(_KeySqlParameter.ParameterName);                                SqlCommand IN_SqlCommand = new SqlCommand(INstringBuilder.ToString(), _SqlConnection);                                IN_SqlCommand.Parameters.Add(_KeySqlParameter);                for(int i=0;i < _SqlParameters.Length;i++) {                    IN_SqlCommand.Parameters.Add(_SqlParameters[i]);                }                            try {                    _SqlConnection.Open();                    IN_SqlCommand.ExecuteNonQuery();                } finally {                    if (_SqlConnection != null) _SqlConnection.Close();                    IN_SqlCommand.Parameters.Clear();                    IN_SqlCommand.Dispose();                }                            } else {                            setValue("creation", DateTime.Now);                System.Text.StringBuilder INstringBuilder = new System.Text.StringBuilder();                int IN_tempCount = 0;                                INstringBuilder.Append(String.Format("INSERT INTO {0} (", _table));                for(int i=0;i < _SqlParameters.Length;i++) {                    if (_SqlParameters[i].Value != null) {                        if (IN_tempCount > 0) INstringBuilder.Append(", ");                        INstringBuilder.Append(_SqlParameters[i].SourceColumn);                        IN_tempCount ++;                    }                }                                INstringBuilder.Append(") Values (");                IN_tempCount = 0;                for(int i=0;i < _SqlParameters.Length;i++) {                    if (_SqlParameters[i].Value != null) {                        if (IN_tempCount > 0) INstringBuilder.Append(", ");                        INstringBuilder.Append(_SqlParameters[i].ParameterName);                        IN_tempCount ++;                    }                }                                INstringBuilder.Append(");SELECT SCOPE_IDENTITY() AS NEWID");                SqlCommand IN_SqlCommand = new SqlCommand(INstringBuilder.ToString(), _SqlConnection);                for(int i=0;i < _SqlParameters.Length;i++) {                    if (_SqlParameters[i].Value != null) {                        IN_SqlCommand.Parameters.Add(_SqlParameters[i]);                    }                }                try {                    _SqlConnection.Open();                    Identity = Convert.ToInt32(IN_SqlCommand.ExecuteScalar());                } finally {                    if (_SqlConnection != null) _SqlConnection.Close();                    IN_SqlCommand.Parameters.Clear();                    IN_SqlCommand.Dispose();                }                            }        }

View Replies View Related

How To Get Around SqlException I'm Getting Because Of IS NOT NULL???

I'm trying to return all the rooms that are in a specific area being selected in a ComboBox and I don't want any rooms that have no MacNo. I would have thought this would do it but they Visual Studio throws me a SqlException "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."

String dbsql = "SELECT a.RoomID " +
" , a.Room " +
" FROM tblRdrRm a " +
" WHERE a.RoomID = (SELECT RoomID " +
" FROM tblRdrInfo r " +
" WHERE r.AreaID = '" + reaid + "' " +
" AND r.MacNo IS NOT NULL ) " +
"ANDa.AreaID = '" + reaid + "' " +

" UNION " +

"SELECT b.RoomID " +
" , b.Room " +
" FROM tblRdrRm b " +
" WHERE b.AreaID = '" + reaid + "' " +
"";

Thanks

View Replies View Related

SqlException.Errors

When anSQLException is thrown there is often more than one error in the SqlException.Errors property. Am I correct in the assumption that the farther down the list of the Errors the more specific th error gets? ie SqlException.Errors[1] is more specific than SqlException.Errors[0]?

View Replies View Related

SqlException When Querying Aspnet_Profile

I am storing employee numbers in the aspnet_Profile table in the PropertyValuesString column. I want to query the aspnet_Profile/PropertyValuesString field to see if a user's employee ID has already been entered.
I get a SqlException error in the App_Code.-u895job.0.cs file (the DAL) when I try to query the aspnet_Profile table using SubSonic (see details below). Is there a better way to query this table? What am I doing wrong?Thanks,
-Allen--------------------------------------------------------
My code behind CS file:AspnetProfile userProfile = new AspnetProfile("PropertyValuesString", txtEmployeeID.Text);if (userProfile != null){  lblAnnounce.Text = "Got it";}
The line in the App_Code.-u895job.0.cs file that throws the error:public AspnetProfile(string columnName, object columnValue){  SetSQLProps();  InitSetDefaults();  LoadByParam(columnName,columnValue);     <-- THE LINE THAT THROWS THE ERROR}
The error from Visual Studio 2008:SqlException was unhandled by user codeThe text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
aspnet_Profile table structure:CREATE TABLE [dbo].[aspnet_Profile]( [UserId] [uniqueidentifier] NOT NULL, [PropertyNames] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [PropertyValuesString] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [PropertyValuesBinary] [image] NOT NULL, [LastUpdatedDate] [datetime] NOT NULL,PRIMARY KEY CLUSTERED ( [UserId] ASC) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GOUSE [WebApp]GOALTER TABLE [dbo].[aspnet_Profile]  WITH NOCHECK ADD  CONSTRAINT [FK__aspnet_Pr__UserI__32767D0B] FOREIGN KEY([UserId])REFERENCES [dbo].[aspnet_Users] ([UserId])GOALTER TABLE [dbo].[aspnet_Profile] CHECK CONSTRAINT [FK__aspnet_Pr__UserI__32767D0B]

View Replies View Related

SQL Errors Can't Be Catched By SQLException

Hi fellows!
I have a problem that just driving me crazy, I have a program that using a web service as a mid tier connects to a SQL Server 2005, I using stored procedures in all my queries through ADO.net 2.0 data adapters, the problem that I can’t catch any exceptions in stored procedure except couple of them, like exce permeation denied, but even stuff like key violation or RAISERROR can’t be catched, to rollback my transactions, and this despite severity level of the error, I searched internet, there is couple guys posted similar problems but no body found the solutions, hoping to find one here, the problem that you can’t just ignore this problem because it is cracks the whole logic of the DB!
Please help…

View Replies View Related

SqlException: Invalid Column Name

Hello,
I have a problem with my Update sql server command. The error message is strange :
System.Data.SqlClient.SqlException: Invalid column name 'CMD_DATE_ORDER'. Invalid column name 'CMD_REF_CLIENT'. at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior,
RunBehavior runBehavior, Boolean returnStream) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at ASP.addorder_aspx.MasterGrid_Update(Object Sender, DataGridCommandEventArgs E)
in C:Inetpubwwwrootproject1addorder.aspx:line 157
On line 157 I have :
UpdateCommand.ExecuteNonQuery()

The Update code :
Sub MasterGrid_Update(Sender As Object, E As DataGridCommandEventArgs)
' update the database with the new values
' get the edit text boxes
Dim dateCom As String = CType(e.Item.FindControl("dateCom"), TextBox).Text
Dim NumBon As String = CType(e.Item.FindControl("NumBon"), TextBox).Text
Dim NomDest As String = CType(e.Item.FindControl("NomDest"), TextBox).Text
Dim NovoieDest As String = CType(e.Item.FindControl("NovoieDest"), TextBox).Text
Dim nomvoieDest As String = CType(e.Item.FindControl("nomvoieDest"), TextBox).Text
Dim cpDest As String = CType(e.Item.FindControl("cpDest"), TextBox).Text
Dim villeDest As String = CType(e.Item.FindControl("villeDest"), TextBox).Text
Dim paysDest As String = CType(e.Item.FindControl("paysDest"), TextBox).Text
Dim telDest As String = CType(e.Item.FindControl("telDest"), TextBox).Text
Dim dateExp As String = CType(e.Item.FindControl("dateExp"), TextBox).Text

Dim myConnection As New SqlConnection(strConnect)
Dim UpdateCommand As SqlCommand = new SqlCommand()
UpdateCommand.Connection = myConnection
' Add to CLIID_LGN the selected value in the DropDownList
Dim cliid As String
cliid = Trim(DDL.SelectedItem.Value)

If AddingNew = True Then
UpdateCommand.CommandText = "INSERT INTO Commandes (CMD_DATE_ORDER, CMD_NUM_BON_ORDER, CMD_NOM_DEST, CMD_NOVOIE_DEST, CMD_NOMVOIE_DEST, CMD_CP_DEST, CMD_VILLE_DEST, CMD_PAYS_DEST, CMD_TEL_DEST,
CMD_DATE_EXPED, CMD_REF_CLIENT) VALUES ('" & dateCom & "','" & NumBon & "','" & NomDest & "','" & NovoieDest & "','" & nomvoieDest & "','" & cpDest & "','" & villeDest & "','" & paysDest & "','" & telDest & "',
'" & dateExp & "', '" & cliid & "')"
Else
UpdateCommand.CommandText = "UPDATE Client SET CMD_DATE_ORDER=@dateCom, CMD_NUM_BON_ORDER = @NumBon, CMD_NOM_DEST = @NomDest, CMD_NOVOIE_DEST = @NovoieDest, CMD_NOMVOIE_DEST = @NomvoieDest,
CMD_CP_DEST = @cpDest, CMD_VILLE_DEST = @villeDest, CMD_PAYS_DEST = @paysDest, CMD_TEL_DEST = @telDest, CMD_DATE_EXPED = @dateExp WHERE CMD_REF_CLIENT = '" & cliid & "'"
End If

UpdateCommand.Parameters.Add("@dateCom", SqldbType.SmallDateTime, 4).Value = Trim(dateCom)
UpdateCommand.Parameters.Add("@NumBon", SqldbType.NVarChar, 10).Value = Trim(NumBon)
UpdateCommand.Parameters.Add("@NomDest", SqldbType.NVarChar, 50).Value = Trim(NomDest)
UpdateCommand.Parameters.Add("@NovoieDest", SqldbType.NVarChar, 5).Value = Trim(NovoieDest)
UpdateCommand.Parameters.Add("@nomvoieDest", SqldbType.NVarChar, 80).Value = Trim(nomvoieDest)
UpdateCommand.Parameters.Add("@cpDest", SqldbType.NVarChar, 5).Value = Trim(cpDest)
UpdateCommand.Parameters.Add("@villeDest", SqldbType.NVarChar, 35).Value = Trim(villeDest)
UpdateCommand.Parameters.Add("@paysDest", SqldbType.NVarChar, 35).Value = Trim(paysDest)
UpdateCommand.Parameters.Add("@telDest", SqldbType.NVarChar, 14).Value = Trim(telDest)
UpdateCommand.Parameters.Add("@dateExp", SqldbType.SmallDateTime, 4).Value = Trim(dateExp)

' execute the command
Try
myConnection.Open()
UpdateCommand.ExecuteNonQuery()

Catch ex as Exception
Message.Text = ex.ToString()

Finally
myConnection.Close()

End Try

' Resort the grid for new records
If AddingNew = True Then
MasterGrid.CurrentPageIndex = 0
AddingNew = false
End If

' rebind the grid
MasterGrid.EditItemIndex = -1
BindMasterGrid()
End Sub
I have send a response.write instruction : the values are all good.
In the sql server database, the syntax of this 2 fields CMD_DATE_ORDER and CMD_REF_CLIENT are good.

Can you help me for this problem ?
Thanks.

View Replies View Related

SQLException - How Can I Get The Query That Caused It?

Using ADO.Net and SQL 2005, we have an exception handler in one of our .VB classes. We extract all the information from the exception and dump the stack into an email, but we would also like to see the query that caused the exception.

Is there an easy way to get the offending query without puttinga try-catch around the hundreds of queries?

Thanks.

View Replies View Related

SQLException Unhandled By User Code

Cannot insert the value NULL into column 'PortfolioID', table 'SazamaBuilders.dbo.Portfolio'; column does not allow nulls. INSERT fails.The statement has been terminated.
 Looking for help with the correcting this.
This is the complete error message I am receiving. When debugging and I try to save something the error comes up right next to objportfolio.Save(). The following is my code for the save button:Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
 
If Page.IsValid ThenDim objportfolio As New BusinessObjects.Portfolio
objportfolio.LoadByPrimaryKey(ViewState("ItemID"))
If objportfolio.es.HasData = False Then
objportfolio.AddNew()
End IfWith objportfolio
.portfolioName = Me.txtportfolioName.Text
' See if the directory is there, if not, create one
If IO.Directory.Exists(Server.MapPath("../Gallery/")) = False ThenIO.Directory.CreateDirectory(Server.MapPath("../Gallery/"))
End If
If Me.FileUpload1.HasFile ThenMe.FileUpload1.SaveAs(Server.MapPath("../Gallery/" & Me.FileUpload1.FileName))
.Filename = Me.FileUpload1.FileName
End If
End With
'Now save the portfolio
objportfolio.Save()
'Cleanup
objportfolio = NothingResponse.Redirect("./manage_portfolio.aspx")
End If
 
End Sub
 
 

View Replies View Related

SqlException (0x80131904): Timeout Expired.

I am running Windows 2003 Server, ASP.NET 2.0, IIS, SQL 2005, and VS 2005.  This is a Dell dual 3.0GHz with 3GB RAM.
Off and on we get an error like below on simple queries that should take less than a second to run.  Then if we wait a while and try again, it will run fast.  The error states a timeout problem.  As we look at RAM and CPU usuage, we are fine.  However, SQL Profiler does show that the duration for some of these very simple queries take forever.  One example query selects a row from a table with only 19 rows.

Server Error in '/' Application.


Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.The statement has been terminated.
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: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.The statement has been terminated.Source Error:



Line 39:
Line 40: MyConnUpdate.Open()
Line 41: cmdUpdate.ExecuteNonQuery()
Line 42: MyConnUpdate.Close()
Line 43: End SubSource File: d:wwwrootwebewsblogviewDetails.aspx.vb    Line: 41 Stack Trace:



[SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +857466
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +735078
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1838
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +149
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +886
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +415
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135
viewDetails.IncrementViewCount(Int32 newsID) in d:wwwrootwebewsblogviewDetails.aspx.vb:41
viewDetails.Page_Load(Object sender, EventArgs e) in d:wwwrootwebewsblogviewDetails.aspx.vb:8
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061



Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42
 
Any help would be greatly appreciated!
Thanks,
Nate Dogg

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

Sqlexception Was Handled By User Code..... What Does This Mean?

im a new user of asp.net 2.0 and downloaded the 14 part video at microsoft's website.After viewing part 4 of it and literally copying the code that i've seen in the video, i encounteredthis error when i decided to run my copied asp.net application when this message popped up. I dontknow what im going to do with this message or how to solve it since im new to asp.net 2.0. Can anyone guide me or give their opinion so i could fix this? thanks!Sqlexception was handled by user codeAN error occured while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default SQL Server does not allo remote connection...

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

SQLException On Insert - TimeStamp Column

ASP.NET application, MS SQL DB, and a table with a timestamp(8) column.

Error:
Cannot insert a non-null value into a timestamp column. Use INSERT with a column list or with a default of NULL for the timestamp column.

I'm using an SQLDataAdapter and typed DataSet, inserting a row into the dataset, and calling Update() to send changes to the DB.

The thing that baffles me about receiving this error, is that the DB column can be null and I get this error wheter I attempt to insert NULL or a valid byte array into the column.

(No - I am not trying to insert a datetime into the column.)

The error just doesn't seem too descriptive of the problem I'm having, and I'm quite confused.

All help greatly appreciated!

Slezak

View Replies View Related







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