Update Command Exception

Apr 15, 2008

HI

i make form to update some data in table

the code:protected void Update_Click(object sender, EventArgs e)

{SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=AinShams;Integrated Security=True");

con.Open();SqlCommand cmd = con.CreateCommand();

int iid = int.Parse(DropDownList1.SelectedValue);string name2 = DropDownList1.SelectedItem.Text;

string des2 = txt_dsc.Text;string loc2 = txt_loc.Text;

int act=-1;if (active_check.Checked == true)

{

act = 1;

}

else

{

act = 0;

}int yearsc = int.Parse(txt_yc.Text);

int pr = -1;if (prep_ck.Checked == true)

{

pr = 1;

}

else

{

pr = 0;

}

cmd.CommandText = "update Faculties set FacultyName=" +name2+ ",FacultyDescription=" + des2 + ",FacultyLocation=" + loc2 + ",FacultyActive='" + act + "',FacultyYearsCount='" + yearsc + "',FacultyIsPrep='" + pr + "' where FacultyId='" + iid + "'";

//cmd.CommandText = "update Faculties set FacultyName=@name,FacultyDescription=@des,FacultyLocation=@loc,FacultyActive=@act,FacultyYearsCount=@years,FacultyIsPrep=@p where FacultyId=@iid";

// cmd.CommandText = "update Faculties set FacultyDescription=" + des2 + " where FacultyId='" + iid + "'";

//cmd.Parameters.AddWithValue(@name, name);

//cmd.Parameters.AddWithValue(@des, des);

//cmd.Parameters.AddWithValue(@loc, loc );

//cmd.Parameters.AddWithValue(@act, act);

//cmd.Parameters.AddWithValue(@years, yearsc);

//cmd.Parameters.AddWithValue(@p , pr);

//cmd.Parameters.AddWithValue(@iid, iid );

cmd.ExecuteNonQuery();

con.Close();

 }

 

but it give mw exception:


Server Error in '/try' Application.


Invalid column name 'sara'.
Invalid column name 'mayada'.
Invalid column name 'mmmmmm'. 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: Invalid column name 'sara'.
Invalid column name 'mayada'.
Invalid column name 'mmmmmm'.

Source Error:





The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:

1. Add a "Debug=true" directive at the top of the file that generated the error. Example:

  <%@ Page Language="C#" Debug="true" %>

or:

2) Add the following section to the configuration file of your application:

<configuration>
   <system.web>
       <compilation debug="true"/>
   </system.web>
</configuration>

Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.

Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario.
Stack Trace:





[SqlException (0x80131904): Invalid column name 'sara'.
Invalid column name 'mayada'.
Invalid column name 'mmmmmm'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +180
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +68
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +199
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2411
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) +196
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +380
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +115
Manage_Faculties22.Update_Click(Object sender, EventArgs e) +879
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +75
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +97
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4886





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

 

when i click the update button this error appear

sara mayada mmmmm the data i enter in the form

what couse this error please?

Thanx in advance

View 1 Replies


ADVERTISEMENT

Exception Error - Incorrect Syntax Near '('. Inline UPDATE Command

May 4, 2007

Hi,
Here's the code I've used to try and update a new user's IP Address to a Table called Customer who's key field in the UserId:
Getting the Exception Error   "Incorrect Syntax near'('. "                 Any ideas?
protected void ContinueButton_Click(object sender, EventArgs e)
{
//Get the ip address and put it into the customer table - (the instance of this user now exists)
 
MembershipUser _membershipUser = Membership.GetUser(); //This gets the active user if there is someone logged in...
Guid UserId = (Guid)_membershipUser.ProviderUserKey; //This gets the userId for the currently logged in user
string IPAddress = Request.UserHostAddress.ToString();//This gets the IPAddress of the currently logged in user
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
using (System.Data.SqlClient.SqlConnection con =new System.Data.SqlClient.SqlConnection(cs))
{
con.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
 
cmd.CommandText = "UPDATE Customer SET(IP_Address = @IP_Address) WHERE (UserId = @UserId)";
cmd.Parameters.Add("@UserId", System.Data.SqlDbType.UniqueIdentifier).Value = UserId;
cmd.Parameters.Add("@IP_Address", System.Data.SqlDbType.Char, 15).Value = IPAddress;
cmd.ExecuteNonQuery();
 
con.Close();
}
 Thanks.

View 5 Replies View Related

Exception:There Is An Open DataReader Associated With This Command Which Must Be Closed First.

May 3, 2008

the class code:
Dataase.cs: using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml.Linq; using System.Data.SqlClient; using System.Data.Common; using System.Web; /// <summary> /// Summary description for DataBase /// </summary> public class DataBase { private SqlConnection con=new SqlConnection(); private void Open() { if (con==null) { con = new SqlConnection("Data Source=58.17.30.81;Initial Catalog=a1230192748;Persist Security Info=True;User ID=a1230192748;Password=***"); } if (con.State == System.Data.ConnectionState.Closed) { con.ConnectionString = "Data Source=58.17.30.81;Initial Catalog=a1230192748;Persist Security Info=True;User ID=a1230192748;Password=****"; con.Open(); } } public void Close() { if (con != null && con.State != System.Data.ConnectionState.Open) con.Close(); } public DataBase() { // // TODO: Add constructor logic here // } public string liuyan(string id,string sign) { string com=string.Empty; switch(sign) { case "xiaobiaoti": com="Select subject from liuyan where liuyanid='"+id+"'"; break; case "def_message": com="Select message from liuyan where liuyanid='"+id+"'"; break; } SqlCommand myCommand=new SqlCommand(com,con); Open(); try { SqlDataReader sdr=myCommand.ExecuteReader(); if (sdr.Read()) { return sdr[0].ToString(); } else { return ""; } sdr.Close();    //what i have written.} catch (Exception ex) { HttpContext.Current.Response.Write("<script>alert('error:" + ex.Message + "')</script>"); return ""; } finally { myCommand.Dispose(); Close(); } } }
 
it was instantiated once in  aspx.cs code.I invoke liuyan(string id,string sign) twice.The first one is OK and the second one makes an exception.
 

View 3 Replies View Related

Defining Command,commandtype And Connectionstring For SELECT Command Is Not Similar To INSERT And UPDATE

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

Strange Exception - Batch Update

Apr 19, 2007

Can anyone help me understand what this means:




Code Snippet

java.sql.BatchUpdateException: com.microsoft.sqlserver.jdbc.SQLServerException: The IOBuffer.process operation returned an unknown packet type:0. Index:41. End:83.TDS_DONEINPROC(-1) TDS_DONEPROC(-2) TDS_DONE(-3) TDS_COLMETADATA(-127)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeBatch(Unknown Source)




I'm trying to do a very simple batch update.

View 7 Replies View Related

Plz Help...update Value In Multiple Db Table Using Single 'update Command'

Mar 18, 2005

hi,friends

we show record from multiple table using single 'selectcommand'.
like....
---------
select *
from cust_detail,vend_detail
---------

i want to insert value in multiple database table(more than one) using single 'insert command'.
is it possible?
give any idea or solution.

i want to update value in multiple database table(more than one) using single 'update command'

i want to delete value in multiple database table(more than one) using singl 'delete command'
it is possible?
give any idea or solution.

it's urgent.

thanks in advance.

View 2 Replies View Related

Is There A Way To Update Multiple Fields Using UPDATE Command

Oct 19, 2005

UPDATE #TempTableESR SET CTRLBudEng = (SELECT SUM(Salaries) from ProjectBudget WHERE Project = @Project)UPDATE #TempTableESR SET CTRLBudTravel = (SELECT SUM(Travels) from ProjectBudget WHERE Project = @Project)UPDATE #TempTableESR SET CTRLBudMaterials = (SELECT SUM(Materials) from ProjectBudget WHERE Project = @Project)UPDATE #TempTableESR SET CTRLBudOther = (SELECT SUM(Others) from ProjectBudget WHERE Project = @Project)UPDATE #TempTableESR SET CTRLBudContingency = (SELECT SUM(Contingency) from ProjectBudget WHERE Project = @Project)above is the UPDATE command i am using in one of my stored procedures. I have to SELECT from my ProjectBudget table 5 times to update my #TempTableESR table. is there an UPDATE command i can use which would let me update multiple fields in a table using one SELECT command?

View 1 Replies View Related

'((System.Exception)($exception)).Message' Threw An Exception Of Type 'System.NotSupportedException'

Jan 16, 2008

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



My table has 4 columns (i have since changed my FavoriteAccount datatype from bit to Integer)
http://i85.photobucket.com/albums/k71/Scionwest/table.jpg

Account type will either be "Checking" or "Savings" when a new row is added, the user will select what they want from a combo box.

Next is a snap shot of my startup form.
http://i85.photobucket.com/albums/k71/Scionwest/form.jpg



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


private void lnkFavoriteAccount_Click(object sender, EventArgs e)

{

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

account.Name = "MyBank Checking Account";

account.AccountType = "Checking";

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

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

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



this.bankAccountTableAdapter1.Update(financesDataSet);

this.financesDataSet.AcceptChanges();

refreshDatabase();

}


the refreshDatabase() code is here:


private void refreshDatabase()

{

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

//Aquire a count of accounts the user has

int numAccounts = financesDataSet.BankAccount.Count;

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

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

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

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

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

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

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

break;

}

}

}


and my form_load code

private void frmMain_Load(object sender, EventArgs e)

{

refreshDatabase();

}


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

[global:ystem.Diagnostics.DebuggerNonUserCodeAttribute()]

public byte FavoriteAccount {

get {

try {

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

}

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

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

}

}

set {

this[this.tableBankAccount.FavoriteAccountColumn] = value;

}

}


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

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

in my refreshDatabase() method it still failed.

When I look, the data has been added into the database, it's just when I try to retreive it now, it bails on me. Am I retreiving the information wrong?

Thanks for any help you guys can offer.

Johnathon

View 1 Replies View Related

The Script Threw An Exception: Exception Of Type 'System.OutOfMemoryException' Was Thrown.

Jan 31, 2007

Hi,

I got an strange problem with one of my packages.

When running the package in VisualStudio it runs properly, but if I let this package run as part of an SQL-Server Agent job, I got the message "The script threw an exception: Exception of type 'System.OutOfMemoryException' was thrown." on my log and the package ends up with an error.

Both times it is exactly the same package on the same server, so I don't know how the debug or even if there is anything I need to debug?

Regards,

Jan

View 2 Replies View Related

Update Command Does Nothing

Aug 10, 2006

I have a database on a server that im trying to update using asp.net.  I tested this on another server and everything worked perfectly.  The test system was set up where the website is hosted.  But the live system is placed on a different server than the webpage.  Does that make a difference? 
Test System
Client -> Website/database
Live System:
Client -> website -> database
I created a user account to use when accessing the database on the live system because i read the double hop causes problems.  By using that account i can access and view the data.  But whenever i update it nothing happens.  NO ERROR either.  It works perfectly but does nothing.  Anyone have any ideas please?!?!?!

View 2 Replies View Related

Update SQL Command

Dec 10, 2007

Hi all, just need a LITTLE help here.  I am very close, I know I am, but just can't seem to fit the last piece in on this.  I have a page that shows current data for a customer and allows you to make changes to the data, then I have a button to push to update the system.  If I hard-code in a value in place of '@Pf_Value' it will update that value, so I know my where is working, just SOMETHING missing in syntax on the set statement or something wrong on my cmd.parameters statement.  Any help would be great!!Protected Sub UpdateButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
Dim sql As String = "update CustomerPOFlexField set [Pf_Value] = @Pf_Value where Pf_property = 'Attrib1' and Pf_CustomerNo = @CustomerNo"Dim newc As String = NewCustomer.Text
Using conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("HCISDataConnectionString").ConnectionString)Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@CustomerNo", DropDownlist1.SelectedValue)cmd.Parameters.Add(New SqlParameter("@Pf_Value", TextBox2.Text))
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Thanks,
Randy

View 16 Replies View Related

SQL Update Command

Jan 8, 2008

Hi all,
Im working in VB web application.Im having some values in some textbox and trying to update it using update command and its not working for me... I used ExecuteNonQuery statement after that. The alert message after that is working for me. But the values i changed in textbox in not updating in my database.
What could be wrong?          cid = lbcid.Text
cname = txtname.Text
contactname = txtconame.Text
tele = Val(txttele.Text)
mob = Val(txtmob.Text)
email = txtemail.Text
genmess = txtgen.Text cmd = New SqlCommand("Update CompanyDetails set CompanyName='" & cname & "',ContactName='" & contactname & "',Telephone=" & tele & ",Mobile=" & mob & ",Generalmess='" & genmess & "',Email='" & email & "'where CompanyId= '" & cid & "'", con)


con.Open()
cmd.ExecuteNonQuery()
Response.Write("<script>alert('Updated')</script>")
 

View 5 Replies View Related

Update Command Help

Nov 5, 2007

I'm using SQL Server Management Studio to do an extremely simple table update (I thought). I wish to fill a newly added table field with a value, however I didn't do this before... What I do is:


UPDATE _t_Computerhuys_MSCRM.dbo.ContactExtensionBase

SET New_Test = "Testvalue"


However then I get the errormessage:

Msg 207, Level 16, State 1, Line 2

Invalid column name 'Testvalue'.


Apparently what I see as a value is being looked at as a column name. I guess it has to do with syntax, but I can't find what's wrong. How to solve?

View 1 Replies View Related

Sql Update With Command.Parameters

Oct 10, 2006

 Im looking for example code to make a sql update... I want to use command.Parameters and variables from text boxes and i'm unsure how to do this...  Please help. This code below doesn't work but it is an example of what i've been working with..  <code>     {               string conn = string.Empty;            ConnectionStringsSection connectionStringsSection = WebConfigurationManager.GetSection("connectionStrings") as ConnectionStringsSection;            if (connectionStringsSection != null)            {                ConnectionStringSettingsCollection connectStrings = connectionStringsSection.ConnectionStrings;                ConnectionStringSettings connString = connectStrings["whowantsConnectionString"];                conn = connString.ConnectionString;                using (SqlConnection connection = new SqlConnection(conn))                using (SqlCommand command = new SqlCommand("UPDATE users SET currentscore=5)", connection))                {                    updateCommand.Parameters.Add("@currentscore", SQLServerDbType.numeric, 18, "currentscore");                    connection.Open();                    command.ExecuteNonQuery();                    connection.Close();                }            }        }</code>   

View 3 Replies View Related

UPDATE Command Not Working

Feb 13, 2007

i am using visual web developer 2005 and SQL Express 2005 and VB as the code behindi have a table called orderdetail and i want to update the fromdesignstatus field from 0 to 1 in one of the rows containing order_id = 2so i am using the following coding in button click event  Protected Sub updatebutton_Click(ByVal sender As Object, ByVal e As System.EventArgs)        Dim update As New SqlDataSource()        update.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ToString()        update.UpdateCommandType = SqlDataSourceCommandType.Text        update.UpdateCommand = "UPDATE orderdetail SET fromdesignstatus = '1' WHERE order_id = '2'"  End Sub  but the field is not updatedi do not know where i have gone wrong in my coding. i am sure that my database connection string is correctplease help me 

View 1 Replies View Related

Question Regarding Using The Sql Update Command.

Jul 10, 2007

Here I have the following command
Dim dtNow As DateTime = DateTime.NowSqlDataSource1.UpdateCommand="Update [db] Set [LW]='TRUE', LWD=dtnow Where [PK]=@PK"What I was ttrying to accomplish was , in my grid view, when someone clicks update, it would automatically set LW to true and set LWD to today's date. No user intervention required. However, I figured the above script would not work. What would I have to do to make LWD = dtnow? I do not want to give the user the option to update anything.
 

View 3 Replies View Related

Help With Booleans With UPDATE Command.

Jul 26, 2007

Hello, I'm using a Gridview to display a list of servers.  Each server has a column in a table called "Enabled."  I want to create a button that is supposed to toggle the value called "Enabled."  I am able to make the button either to set Enabled to true or false, but I don't know how to make it toggle.  Here is the command:UpdateCommand="UPDATE [ServerStatus] SET [Enabled] = 1 WHERE [ServerName] = @ServerName" The button is a buttonfield in the gridview:<asp:ButtonField ButtonType="Button" CommandName="Update" HeaderText="Toggle" ShowHeader="True" Text="Toggle" /> Does anyone know the syntax, or a way to make the button set Enabled to true when it is false, and false when it is set to true? 

View 2 Replies View Related

Problem With Update Command

Aug 2, 2007

Hi,i try to update field 'name' (nvarchar(5) in sql server) of table 'mytable'.This happens in event DetailsView1_ItemUpdating with my own code.It works without parameters (i know, bad way) like this:SqlDataSource1.UpdateCommand = "UPDATE mytable set name= '" & na & "'"But when using parameters like here below, i get the error:"Input string was not in a correct format"Protected Sub DetailsView1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewUpdateEventArgs) Handles DetailsView1.ItemUpdatingSqlDataSource1.UpdateCommand = "UPDATE mytable set name= @myname"SqlDataSource1.UpdateParameters.Add("@myname", SqlDbType.NVarChar, na)SqlDataSource1.Update()End SubI don't see what's wrong here.Thanks for helpTartuffe

View 2 Replies View Related

How To Use Update Command At Sqldatasouce

Sep 24, 2007

 hello all..,i have problem in update sqldatasource,  my code like that:me.sqldatasource.updateparameter(index).defaultvalue=valueme.sqldatasource.update()it can not update data, why?but if i use insert or delete like:me.sqldatasource.insertparameter(index).defaultvalue=valueme.sqldatasource.insert()me.sqldatasource.deleteparameter(index).defaultvalue=valueme.sqldatasource.delete()it can work for insert and delete data...can anyone give me update command code in sqldatasouce? plsss...thx...  

View 11 Replies View Related

SQL Update Command Fails

Jan 5, 2008

 
I have the code as fallows to update my SQL data ;Sub Kaydet(ByVal TickerKod As String, ByVal op1 As Double, ByVal op2 As Double, ByVal op3 As Double, ByVal op4 As Double, ByVal op5 As Double, ByVal op6 As Double, ByVal op7 As Double, ByVal mov1 As Double, ByVal mov2 As Double)
'Dim nop1 As Decimal = FormatNumber(Replace(op1, ",", "."), 2)Dim mysource As New SqlDataSource
mysource.ConnectionString = ("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Stock.mdf;Integrated Security=True;User Instance=True")mysource.UpdateCommand = ("UPDATE StockParametre SET OPT1 = " & FormatNumber(op1, 2) & ", OPT2 = " & FormatNumber(op2, 2) & ", OPT3 = " & FormatNumber(op3, 2) & ", OPT4 = " & FormatNumber(op4, 2) & ", OPT5 = " & FormatNumber(op5, 2) & ", OPT6 = " & FormatNumber(op6, 2) & ", OPT7 = " & FormatNumber(op7, 2) & ", MOVY = " & FormatNumber(mov1, 2) & ", MOVD = " & FormatNumber(mov2, 2) & " WHERE (Stock = '" & TickerKod & "')")
mysource.Update()Response.Write(mysource.UpdateCommand & "<br>")
End Sub
When I call this code inside of Virtual Web Developer it functions perfect and updates the data..There is no problerm
But when I call it like http:// .......myip/updatedata.aspx then I have the error " System.Data.SqlClient.SqlException: Incorrect Syntax near 32
I  see that 32 is the value inside the update command like SET OPT1=107,32, OPT2=25,00, ........and so on Where do I make wrong ?
Thanks

View 4 Replies View Related

Update Command Syntax ...

Feb 3, 2008

Hi here's a bit of code. What am I doing wrong here?  Visual Studio isn't even accepting the Set word on line 56. It deletes it everytime.  What am I doing wrong here? Why is Visual studio putting the parenthese around the table name in 55? I generated an update query for my Websitetableadapter. Here it is:
UPDATE [tblWebSite] SET [Rating] = @Rating, WHERE (([WebSiteID] = @Original_WebSiteID))
How do I use this to update the Rating column after I've done my calculation below?

1    Imports RatingsTableAdapters2    3    4    Partial Class admin_ratings5        Inherits System.Web.UI.Page6    7        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load8            Dim I As Integer = 09            Dim J As Integer = 010           Dim Rating As Integer11           Dim Rate As Decimal12           Dim tblwebsiteAdapter As New tblWebSiteTableAdapter13           Dim tblWebsite As ratings.tblWebSiteDataTable14           tblWebsite = tblwebsiteAdapter.GetData()15           For Each tblwebsiteRow As ratings.tblWebSiteRow In tblWebsite16               Rate = 017               Dim tblLinkAdapter As New tblLinkTableAdapter18               Dim tblLink As ratings.tblLinkDataTable19               Dim tblLinkTot As ratings.tblLinkDataTable20               tblLink = tblLinkAdapter.GetSuccessfulExchanges(tblwebsiteRow.WebSiteID)21               tblLinkTot = tblLinkAdapter.GetTotalLinks(tblwebsiteRow.WebSiteID)22               For Each tbllinkRow As ratings.tblLinkRow In tblLink23                   If tbllinkRow.LinkID < 1 Then24                       I = 0.125                   Else : I = I + 126                   End If27               Next28               If I <> 0 Then29                   For Each tbllinktotrow As ratings.tblLinkRow In tblLinkTot30                       If tbllinktotrow.LinkID < 1 Then31                           J = 0.132                       Else : J = J + 133                       End If34                   Next35               End If36               If I <> 0 And J <> 0 Then37   38                   Rate = I / J39                   If Rate <= 0.3 Then40                       Rate = 041                   End If42                   If Rate <= 0.5 Then43                       Rate = 144                   End If45                   If Rate <= 0.65 Then46                       Rate = 247                   End If48                   If Rate <= 0.75 Then49                       Rate = 350                   End If51               End If52   53               Response.Write(tblwebsiteRow.WebSiteID & " " & tblwebsiteRow.SiteURL & " Rating: " & Rate & "54               I = 055               J = 056               Update(tblWebsite)57               Rating = Rate58               where(tblwebsiteRow.WebSiteID <> 0)59           Next60       End Sub61   End Class 

View 34 Replies View Related

Why Is My Update Command Not Working

Feb 18, 2008

hi, i am tryuing to use the gridview as means for the user to be able to edit delete and update columns of the database. however when it is run in the browser it allows the user to edit the fields but when i click on the update button it throws an error. can someone please offer me advice on how i can sort this problem out or provide me with any examples as i cant see what the error is. i used the option in edit columns which allows you to specify you want update delete etc controls added to the gridview. how can i make it so it supports updating? thank you
Updating is not supported by data source 'SqlDataSource1' unless UpdateCommand is 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.NotSupportedException: Updating is not supported by data source 'SqlDataSource1' unless UpdateCommand is specified.Source Error:



An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

View 2 Replies View Related

Use Update Command In Code Behind

Apr 18, 2008

 Hi I and using gridview. And binding the data in the code behind.I need to use update command in code behind. How do I achieve this?  I  protected void lookUP (object sender, EventArgs e)
{
string strSql, strConn;

System.Text.StringBuilder whereClause = new System.Text.StringBuilder();

strConn = ConfigurationManager.ConnectionStrings["drake_CSMConnectionString1"].ConnectionString;

SqlConnection Conn = new SqlConnection(strConn);

if (newClientName.Text != "")
whereClause.Append("'" + newClientName.Text + "'");

strSql = "SELECT * FROM [ftsCSM] where [client_name] = " + whereClause.ToString();

SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, Conn);

DataSet ds2 = new DataSet();

dataAdapter.Fill(ds2, "ftsCSM");

DataTable dataTable2 = ds2.Tables["ftsCSM"];

int totalRec = dataTable2.Rows.Count;

Clients.DataSource = ds2;
Clients.DataBind();

} // end of lookup()
 

View 1 Replies View Related

Update Command Not Writing To Db

May 31, 2008

I thought this would work.  I use this code to update another table in another page. In this page, after someone has cast their vote for an article, the article db is updated for the current rating.  It reads all the votes so far and takes and average and is supposed to write this number to the article database. There are 2 columns. ArticleRating is a decimal and is the average and ArticleReaders is the total number of votes. 
The response.write in lines 3 and 4 are the correct numbers appearing in my upper left corner of the page. They are not getting written to the db.  Can someone help me understand why this is the case? 1
2 Public Function UpdateRating(ByVal ArticleID As Integer, ByVal ArticleRating As Decimal, ByVal Votes As Integer) As Boolean
3 Response.Write("Values: " & ArticleRating)
4 Response.Write("Votes: " & Votes)
5
6 Dim con As New SqlConnection(DataFuncs.GetConnectionString)
7 Const sSQL As String = "UPDATE tblArticle SET ArticleRating = @ArticleRating, ArticleReaders=@Votes WHERE ArticleID = @ArticleID"
8 Dim xSqlCommand As SqlCommand = New SqlCommand(sSQL, con)
9 Try
10 xSqlCommand.Parameters.Add("@Rating", Data.SqlDbType.Decimal)
11 xSqlCommand.Parameters("@Rating").Value = Rating
12 xSqlCommand.Parameters.Add("@Article", Data.SqlDbType.Decimal)
13 xSqlCommand.Parameters("@ArticleID").Value = ArticleID
14 con.Open()
15 xSqlCommand.ExecuteNonQuery()
16 con.Close()
17 Return True
18 Catch ex As Exception
19 Return False
20 Throw ex
21 Finally
22 xSqlCommand.Dispose()
23 con.Dispose()
24 End Try
25 End Function
 

View 7 Replies View Related

Using Two Or Three Tables In An Update Command

Jun 15, 2004

i want to update a table where a linked table is a certian value
for example

i have a table that queues up calls and has whether they have been contacted or not as a boolean value.

but if the call is closed in another way i would like to update that table where the linked location table has a certian value

but in the query analizer it will only let you use one table to update is there another way to do this?

View 2 Replies View Related

Trigger Update Command

Mar 3, 2007

Hi
I've created this simple trigger that will insert records into another table when an insert has occurred on another.

table A
table B


CREATE TRIGGER [TG_MYTRIGGER]
ON [dbo].[A]
AFTER INSERT
AS
Begin
INSERT B (date, id)
Select DISTINCT i.date,i.id
from inserted i
End



What i cant figure out is how to insert the date plus one month into table B

so instead of just inserting into the second table the i.date i want the i.date + one month.

Does anyone know how this could be done.

many thanks

Bil

View 1 Replies View Related

Help With Update Query Command Problem

Dec 25, 2006

Hi all,
 
I have this store procedure  as follows:
 
Create Proc UpdateProblem@ProblemID int,@CompanyName varchar (50),@Firstname varchar (50),@Lastname Varchar (50),@Address varchar (50),@Postcode varchar (50),@City varchar (50),@Phone varchar (50),@Cutype varchar (50),@ProDescript varchar (50),@Sol varchar (50),@Email varchar (50)
 
as Update Problemset CompanyName = @CompanyName,Firstname = @Firstname,Lastname = @Lastname,Address = @Address,PostCode = @Postcode,City = @City,Phone = @Phone,Cutype = @Cutype,ProDescript = @ProDescript,Sol = @Sol,Email = @Email
where ProblemID = @ProblemID
 when I test the querry
exec UpdateProblem10004, 'Toro AS','Mike','Tullas','Togo Street','G34 5TT','New York','06582531','Private','Machine is dead','Replace motherboard','goo@ht.com'
what happen is that when I ran the querry instead of updating the specifc row of 1004 the querry will just update the whole rows in the table  with the same data.
 Please help.  I have set the ProblemID as the Primary key.
 

View 5 Replies View Related

Update Command Is Updating All My Records!

Feb 16, 2007

I wrote a sproc which does four things:
1.  It looks at an option master to see if the record exists before inserting a new one
2.  If the record is not there it inserts the optino record
3.  Once the record is inserted I have to run a CASE statement on the record to determine its level
4.  Once the level is determined, the record needs to be updated with the correct level.
1-3 work fine (when run without the update command).
However, even though I set a criteria, UPDATE still updates and not the one records.
Any idea why? set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

--CREATE PROCEDURE [dbo].[sp_AddNewOption_OptionMaster_WithLevel]


@BuilderIDint,
@OptionIDINT,
@CommunityID INT,
@PhaseID INT,
@SeriesID INT,
@PlanID INT,
@ElevationID INT,
@CurrentSalesPrice Smallmoney,
@LocalComments Nvarchar (500),
@RoomID int,
@Package bit,
@Active bit

AS

--check to see if the option record exists

IF EXISTS (SELECT 1 FROM optionmaster WHERE BuilderID = @BuilderID AND OptionID = @OptionID AND CommunityID = @CommunityID AND PhaseID = @PhaseID AND PlanID = @PlanID AND ElevationID = @ElevationID)

BEGIN
SELECT ' This option already exists in your Option Master'
END
ELSE BEGIN

--if the option record option does not exist, insert it

INSERT INTO [OptionMaster] ([BuilderID], [OptionID], [CommunityID], [PhaseID], [SeriesID], [PlanID], [ElevationID], [CurrentSalesPrice], [LocalComments], [RoomID], [Package], [Active], [DateAdded], [DateAvailable], [SalesPriceEffective], [OptionLevel])
VALUES (@BuilderID, @OptionID, @CommunityID, @PhaseID, @SeriesID, @PlanID, @ElevationID, @CurrentSalesPrice, @LocalComments, @RoomID, @Package, @active, GETDATE(), GETDATE(), GETDATE(),'10' )

SELECT ' Added to Option Master Successfully'
END

--once the option record is inserted, case it to find the its level (1-9)
--update the record with the approciate level.

UPDATE Optionmaster
SET optionlevel (

SELECT CASE WHEN CommunityID = '0' AND PhaseID = '0' AND PlanID = '0' AND ElevationID = '0' THEN '9' WHEN CommunityID = '0' AND PhaseID = '0' AND
PlanID > '0' AND ElevationID = '0' THEN '8' WHEN CommunityID = '0' AND PhaseID = '0' AND PlanID > '0' AND
ElevationID > '0' THEN '7' WHEN CommunityID > '0' AND PhaseID = '0' AND PlanID = '0' AND ElevationID = '0' THEN '6' WHEN CommunityID > '0' AND
PhaseID = '0' AND PlanID > '0' AND ElevationID = '0' THEN '5' WHEN CommunityID > '0' AND PhaseID = '0' AND PlanID > '0' AND
ElevationID > '0' THEN '4' WHEN CommunityID > '0' AND PhaseID > '0' AND PlanID = '0' AND ElevationID = '0' THEN '3' WHEN CommunityID > '0' AND
PhaseID > '0' AND PlanID > '0' AND ElevationID = '0' THEN '2' WHEN CommunityID > '0' AND PhaseID > '0' AND PlanID > '0' AND
ElevationID > '0' THEN '1'
END AS OptionLevel --provides the option level required to update the record
FROM optionmaster
WHERE (BuilderID= @BuilderID And OptionID = @OptionID and CommunityID = @CommunityID AND PhaseID = @PhaseID AND PlanID = @PlanID AND ElevationID = @ElevationID))
--even through I specify the above criteria, it upates all records. 
 
 

View 9 Replies View Related

Problem With Update Command With Parameters

Aug 2, 2007

Hi,i try to update field 'name' (nvarchar(5) in sql server) of table 'mytable'.This happens in event DetailsView1_ItemUpdating with my own code.It works without parameters (i know, bad way) like this:SqlDataSource1.UpdateCommand = "UPDATE mytable set name= '" & na & "'"But when using parameters like here below, i get the error:"Input string was not in a correct format"Protected Sub DetailsView1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewUpdateEventArgs) Handles DetailsView1.ItemUpdatingSqlDataSource1.UpdateCommand = "UPDATE mytable set name= @myname"SqlDataSource1.UpdateParameters.Add("@myname", SqlDbType.NVarChar, na)SqlDataSource1.Update()End SubI don't see what's wrong here.Thanks for helpTartuffe

View 4 Replies View Related

Sql Update Command With Variable As ColName

May 7, 2008

Hello All
 I m trying to update a table whose col name will be read from another table.
For e.g. Table1 gives the result:
'emp1',   1,   'John'
'emp2',   2,   'Mike'
Now in the second table, i need to update the table with Col name  = 'Emp1' and then from the second row (above), I need to update Col name= 'Emp2'
I need to write one Update Statement which will handle all the cases. I tried
Update Table2 set @VariableName = .......
but didnt work...
How can i do that ?

View 7 Replies View Related

How To Trigger The Update Command Of The SQLDataSource

Jun 13, 2006

Hi - I'm using .net2, and have a gridview, populated by a SQL Datasource (Edit, Insert, Delete, Select).
Like we all used to do with the datagrid, I've added text boxes into the footer, and a link button, which I'd like to use to fire the Update command.
How do I get the link button to trigger the update command?
Thanks, Mark

View 1 Replies View Related

How To Use OLE DB Command To Update A Derived Column

Jul 19, 2007

Hi,

In my SSIS package,

1. I read from a source namely SOURCE. SOURCE is defined like

CREATE TABLE SOURCE

( f1 int, f2 int, f3 int, id int)

, where f1 is unique and id is always null after reading.

2. pass it to a Slow Change Dimension control to separate the new records and changed records

Then for new records,

3. link to a Derived Column control to add in some new columns

4. link to a OLE DB Command control to update field id before write to destination



In Step 4, I use the command :



INSERT INTO global_id_pool

SELECT MAX(id) + 1

FROM global_id_pool



UPDATE SOURCE

SET id =

(SELECT MAX(id) FROM global_id_pool)

WHERE f1 = ?



Using the command, the parameter can't be recognised with an error reported in BIDS. So eventually I had to change the query to the following to make it work



UPDATE SOURCE

SET id =

(SELECT MAX(id) + 1 FROM global_id_pool)



INSERT INTO global_id_pool

SELECT MAX(id) + 1

FROM global_id_pool



I don't mind the parameter can't be added. But after running, I found id field in the table after the OLE DB Command control is still NULL while the field in the SOURCE table in database is updated. So it seems the OLE DB Command worked on database but the data in memory cache wasn't affected.



So I just wonder if there is way to UPDATE the cache in OLE DB Command control. Many thanks for any help.

View 1 Replies View Related

Incorrect Syntax Near [SQL UPDATE COMMAND] &> Cmd.ExecuteNonQuery()

Nov 7, 2007

Please let me know what is wrong with my code below. I keep getting the "Incorrect syntax near 'UpdateInfoByAccountAndFullName'." error when I execute cmd.executenonquery.  I highlighted the part that errors out.  Thanks a lot.  ---------------------------------------------------------------------------------------------------------------------------         public bool Update(                string newaccount, string newfullname, string rep, string zip,                string comment, string oldaccount, string oldfullname            )        {            SqlConnection cn = new SqlConnection(_connectionstring);            SqlCommand cmd = new SqlCommand("UpdateInfoByAccountAndFullName", cn);            cmd.Parameters.AddWithValue("@newaccount", newaccount);            cmd.Parameters.AddWithValue("@newfullname", newfullname);            cmd.Parameters.AddWithValue("@rep", rep);            cmd.Parameters.AddWithValue("@zip", zip);            cmd.Parameters.AddWithValue("@comments", comment);            cmd.Parameters.AddWithValue("@oldaccount", oldaccount);            cmd.Parameters.AddWithValue("@oldfullname", oldfullname);            using (cn)            {                cn.Open();                return cmd.ExecuteNonQuery() > 1;            }        }

View 12 Replies View Related







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