Hello to everyone, I have this problem If I use this code when I try to update a record in my sql database It does not do anything. This is the code. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim myconn As New SqlConnection("Data Source=.;Initial Catalog=SistemaIntegral; user id=sa") Dim mycmd As New SqlCommand("presup", myconn) mycmd.CommandType = CommandType.StoredProceduremycmd.parameters.Add(New SqlParameters("@txtClave", SqlDbtype.int,4)).Value=txtClave.textmycmd.parameters.Add(New SqlParameters("@txtForig", SqlDbtype.varchar,50)).Value=txtFOrig.textmycmd.parameters.Add(New SqlParameters("@txtFmod", SqlDbtype.varchar,50)).Value=txtFmod.textmycmd.parameters.Add(New SqlParameters("@txtFeje", SqlDbtype.varchar,50)).Value=txtFeje.textmycmd.parameters.Add(New SqlParameters("@txtPorig", SqlDbtype.varchar,50)).Value=txtPorig.textmycmd.parameters.Add(New SqlParameters("@txPmod", SqlDbtype.varchar,50)).Value=txtPmod.textmycmd.parameters.Add(New SqlParameters("@txtPeje", SqlDbtype.varchar,50)).Value=txtPeje.text mycmd.parameters.Add(New SqlParameters("@txtClave", SqlDbtype.int,4)).Value=txtClave.text myconn.Open() mycmd.ExecuteNonQuery() myconn.Close() mycmd.Dispose() myconn.Dispose() End Sub This is the code for the procedure called "presup" in SQL 2000 Server.CREATE PROCEDURE [presup](@txtClave [int],@txtForig [varchar](50),@txtFmod [varchar](50),@txtFeje [varchar](50),@txtPorig [varchar](50),@txtPmod [varchar](50),@txtPeje [varchar](50),@txtIdPresupuesto [int])as Update [Presupuesto]Set [IdClave]=@txtClave,[orig]=@txtForig,[moda]=@txtFmod,[ejer]=@txtFEje,[origr]=@txtPorig,[modar]=@txtPmod,[ejerr]=@txtPejeWhere ([IdPresupuesto]=@txtIdPresupuesto)GO When I click the Update button of my webform it does not do anything. Please Help me I am new to Visual Studio.Net 2003. (2 weeks ago I started using Visual Studio)
Hey Guys, I'm not sure if anyone can help me with this but I am trying to achieve the following: I have a row (In this case it is information on a fix) and on a button click I am trying to get it to "archive" it. At the moment I have it so that it it takes the current information and adds it to the archive table adding an archive date. The thing that I am struggling with is incrementing the version number. So, I need it to (in these steps I think) - Look for existance of the other entires of that ID, look for the version number that is related to the newest date of those knowledgeIDs and then add 1 to it. If that knowledgeID doesnt exist then add it as one. My current code is below: Thanks in Advance =) C# Codeprotected void Page_Load(object sender, EventArgs e) {UserName = (string)Session["UserName"]; Label4.Text = UserName + " Is Current Logged In";UserType = (string)Session["UserType"];if ((Session["UserName"] != null) & (UserType == "Helpdesk")) {Response.Redirect("Accessrights.aspx"); }else if (Session["UserName"] == null) {Response.Redirect("Login.aspx"); } FixName = "default";Description = "default";File = "default"; ADate = myCalendar.TodaysDate.ToShortDateString(); AddDate = Convert.ToDateTime(ADate);myConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\inetpub\wwwroot\HOF\App_Data\HOF.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;"; }protected void Button1_Click(object sender, EventArgs e) {SqlConnection myConnection = new SqlConnection(myConnectionString); try { FixName = TextBox1.Text; SqlCommand myCommand = new SqlCommand("select * from Knowledge WHERE FixName like '%" + FixName + "%'", myConnection); myConnection.Open();SqlDataReader myReader = myCommand.ExecuteReader();if (myReader.HasRows) {while (myReader.Read()) { TextBox1.Text = myReader["FixName"].ToString();TextBox2.Text = myReader["Description"].ToString(); File = myReader["Location"].ToString();if (File != null) { TextBox3.Text = File; } else {TextBox3.Text = "There is no script avaliable"; }KnowledgeID = myReader["KnowledgeID"].ToString();Add = myReader["DateAdded"].ToString(); } myConnection.Close(); } else {TextBox1.Text = FixName + "Does not Exist. Please try again."; } }catch (Exception ex) { myConnection.Close(); } try Description = TextBox2.Text;File = Convert.ToString(FileUpload1.FileName);if (CheckBox1.Checked == true) {SAPPS = "True"; } else {SAPPS = "False"; } {SqlCommand mycommand2 = new SqlCommand("INSERT INTO Knowledge (FixName, Description, Location, DateAdded, DateArchived, Version, KnowledgeID) SET ('" + FixName + "','" + Description + "','" + File + "','" + Add + "','"+AddDate+"','" + SAPPS + "','"+I NEED A VALUE HERE+"','"+KnowledgeID+"')", myConnection);SqlDataAdapter myDataAdapter = new SqlDataAdapter(mycommand2); sa = mycommand.ExecuteNonQuery(); myConnection.Close(); }catch (Exception ex) { myConnection.Close(); } }
Hi everyone, Im using SSRS 2000 and I was wondering is there a way to create a click button??? I have 2 reports linked with hyperlinks but I wanted to make it look more presentable. So, instead of just clicking on the words, I want them to click the button.
I feel like it must be easy and I'm missing something. Maybe I'm going the wrong way about it too. Basically I've written an append query that needs parameters, but I have no idea how to actually execute it. I'm coming from building apps in MS Access where all of this is really easy. I'm really enjoying learning some things, and did my first MS SQL trigger event tonight, which worked great. I though using a trigger may be an option here, but I need to control the "when" of this append a little more carefully and can't rely on an automated event. I can manually execute the query and it works, but have a button I could press on a form, with the queries on that form would be ideal. I'm basically moving partial data from one table to another. Any help? Again, this seems like it "should" be easy, but I'm not finding info on it. Please talk slowly, as again, I'm coming from Access.
Hello friends Can anyone tell me the means by which I can populate a label or a datagrid by executing a selectcommand statement on the form of my webpage. And what is the best way to retrieve data from a SQL datasource, is it by using separate sqldatasources for each different parts of a page that requires different data from different tables in the same database or by using a tableadapter to retrieve the data for the best performance? Thanks for replying for my previous questions. It was helpful and great in my program implementation. Thank you
i am using 2 textbox to search name and instituition of some students. on button click need to display the result on gridview. but i dont get any result.. pl adviceSqlDataSource1.SelectCommand = "SELECT Sname, Address, Instituition, Role, Testgroup, Email FROM std_det WHERE (Sname LIKE '%'+@Param1+'%') AND (Instituition = 'RASET') AND (Role LIKE '%'+@Param2+'%') AND (Instituition = 'RASET')"; name.ControlID = "TextBox3"; name.DefaultValue = "%"; name.Name = "Param1"; name.PropertyName = "Text"; inst.ControlID = "TextBox4"; inst.DefaultValue = "%"; inst.Name = "Param2"; inst.PropertyName = "Text"; //SqlDataSource1.Select(DataSourceSelectArguments.Empty); SqlDataSource1.SelectParameters.Add(name); SqlDataSource1.SelectParameters.Add(inst); SqlDataSource1.DataBind(); //DataView dv = (DataView)this.SqlDataSource1.Select(DataSourceSelectArguments.Empty); GridView2.DataSourceID = "SqlDataSource1"; GridView2.DataBind();
I am new to ASP.NET so please excuse what may seem like a dumb question. I have a stored procedure that I need to run when the user clicks on our submit button. I am using Visual Studio 2005 and thought I could use the SqlDataSOurce Control. IS it possible to us the control or do I need to create a connection and call the stored procedure in the the button_click sub? Thanks in advance MF
Hi everyone.I am trying to write 2 INSERT INTO statements into a Button click event. Both statements go to the same database but differnet tables. The first statement works fine but the 2nd causes an error with the Try, Catch, Finally statement. When I remove the ExecuteNonQuery from the 2nd statement, the 2nd INSERT INTO statement fails to work. Any help would be brilliant. Thanks! Private Sub btnInsertChange_Click(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs) Handles btnInsertChange.Command 'Insert Guide changes into ChangesReport table in sql server Me.SqlCommandThemeTest.Connection = Me.SqlConnection1 Dim Name As String Dim values As String Dim sSQL As String Name = "Theme, Guide, GuidePage, PageType, ChangeCategory, ChangeFrom, ChangeFromText, ChangeTo, ChangeToText ContentManager" values = "lstTheme, lstGuideName, lstGuidePage, lstPageType, lstChangeCategory, lstChangeFrom, txtChangeFrom, lstChangeTo, txtChangeTo, Label1" SqlCommandThemeTest.CommandText = "INSERT INTO dbo.ChangesReport (Theme, Guide, GuidePage, PageType, ChangeCategory, ChangeFrom, ChangeFromText, ChangeTo, ChangeToText, ContentManager) VALUES (@themeValue, @guideValue, @guidepageValue, @pagetypeValue, @changecategoryValue, @changefromValue, @changefromtextValue, @changetoValue, @changetotextValue, @contentmanagerValue)" SqlCommandThemeTest.Parameters.Add("@themeValue", lstTheme.SelectedItem.Text) SqlCommandThemeTest.Parameters.Add("@guideValue", lstGuideName.SelectedItem.Text) SqlCommandThemeTest.Parameters.Add("@guidepageValue", lstGuidePage.SelectedItem.Text) SqlCommandThemeTest.Parameters.Add("@pagetypeValue", lstPageType.SelectedItem.Text) SqlCommandThemeTest.Parameters.Add("@changecategoryValue", lstChangeCategory.SelectedItem.Text) SqlCommandThemeTest.Parameters.Add("@changefromValue", lstChangeFrom.SelectedItem.Text) SqlCommandThemeTest.Parameters.Add("@changefromtextValue", txtChangeFrom.Text) SqlCommandThemeTest.Parameters.Add("@changetoValue", lstChangeTo.SelectedItem.Text) SqlCommandThemeTest.Parameters.Add("@changetotextValue", txtChangeTo.Text) SqlCommandThemeTest.Parameters.Add("@contentmanagerValue", Label1.Text) Try Me.SqlConnection1.Open() Me.SqlCommandThemeTest.ExecuteNonQuery() Catch ex As Exception Response.Write(ex.ToString) Finally Me.SqlConnection1.Close() End Try 'Insert textbox to ChangeLogFrom ddl Me.CmdDDLFromUpdate.Connection = Me.SqlConnection1 Name = "ChangeFromText" values = "txtChangeFrom" sSQL = "INSERT INTO dbo.Change Log From (ChangeLogFrom) VALUES (@changelogfromValue)" Me.CmdDDLFromUpdate.Parameters.Add("@changelogfromValue", txtChangeFrom.Text) Try Me.SqlConnection1.Open() Me.CmdDDLFromUpdate.ExecuteNonQuery() Catch ex As Exception Response.Write(ex.ToString) Finally Me.SqlConnection1.Close() End Try
i am using Asp.net , C# , sql server 2005. i made one rdl report and called it from server (win2003). it worked successfully . but when i give print for the same report(through reportviewer control print option). Client machine restart. Same thing happened on four machine that were in win2000.
How can i confirm that the data entered within the standard controls and after the click event for the particular sql query the data is been stored in the database tables (depending insert,update,delete).I want to display the different messages on the click event and that after the changes made into the tables.How can i do it ?? I m using ASP.Net with C#,VB and the sql server to store data.I also want to know where are the database tables exactly get stored which are made in the Microsoft SQL Server Management Studio Express.I want to use as the existing item in .Net but could not find.. Thanxs...
I have a form that contains data that some of which needs to be inserted into one table and the rest updated to another table. I want this to happen on a single button click. Is this possible?Here's what I have so far: String id = parm_tb_tktid.Text; String update = parm_tb_desc.Text; String status = parm_cb_status.Text; SqlCommand cmd = new SqlCommand("Insert into History (tkt_id, hist_desc) values(@parm_tb_tktid, @parm_tb_desc)", HelpdeskConnectionString); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@parm_tb_tktid", id); cmd.Parameters.AddWithValue("@parm_tb_desc", update); SqlCommand cmd1 = new SqlCommand("Update Ticket (tkt_status) values(@parm_cb_status) where tkt_id = @parm_tb_tktid)", HelpdeskConnectionString); cmd1.CommandType = CommandType.Text; cmd1.Parameters.AddWithValue("@parm_cb_status", status); HelpdeskConnectionString.Open(); cmd.ExecuteNonQuery(); cmd1.ExecuteNonQuery(); HelpdeskConnectionString.Close(); parm_tb_tktid.Text = String.Empty; parm_tb_desc.Text = String.Empty; parm_cb_status.Text = String.Empty;I know it isn't right, but I can't find any info on why it's wrong and how to code it properly.
Hello, I need to know how I can make a button on my page send the Time of Click, to a table in a database, and repeat this everytime the button is clicked. Thanks for any guidance on this matter
Hi all! I'm a newbie when it comes to SSIS and web development (I'm currently in school for Mechanical Engineering). I'm trying to develop a website in which I can upload an excel file and have the contents written to a SQL database. I have been successful in creating a package in which I point to an excel file and it writes the contents to the desired database. With this, I was hoping that I can modify my website to take the file which is being uploaded, change the name, and then have the SSIS package run, in which it will look for the named file in a certain directory and upload the contents to the SQL server.
Ideally this would be the order of events:
User selects and uploads a file to the server (button click) Server renames it and places it in a certain directory SSIS package runs and extracts the data to SQL database
I have written some code to insert a record into the table in BtnAdd click event and I also have a Grid view control to show the table records.
If I click the Add button ,the record gets inserted into the table and shown in the grid correspondingly.But if I refresh teh page,the same data gets inserted again since it fires the Btnclick Event.
Dim cmdLogin As New SqlCommand("select * from UserName where ='" & txtusername.Text & "' and Password='" & txtpassword.Text & "'", conn) Dim dr As SqlDataReader dr =cmdLogin.ExecuteReader()
C#, Webforms, VS 2005, SQL Hi all, quick hit question. I'm trying to update a table with an employee name and hire date. Session variable of empID, passed from a previous page (successfully) determines which row to plop the update into. It's not working even though i compiles and makes it all the way through the code to the txtReturned.Text = "I made it" debug line...Any thoughts? 1 string szInsSql; 2 3 string sConnectionString = "Data Source=dfssql;Database=MyDB;uid=myID;pwd=myPWD"; 4 SqlConnection objConn = new SqlConnection(sConnectionString); 5 6 objConn.Open(); 7 8 szInsSql = "UPDATE empEmployee SET " + 9 "Name = '" + this.txtName.Text + "', " + 10 "HireDate = '" + this.txtHireDate.Text + "', " + 11 "WHERE empID = '" + Session[empID] + "'"; 12 13 SqlCommand objCmd1 = new SqlCommand(szInsSql, objConn); 14 objCmd1.ExecuteNonQuery(); 15 16 txtReturned.Text = "I made it"; It's got to be a ' or a , out of place but I've looked at this code for a half hour straight, trying a variety of changes...and it still doesn't update the DB...Any help would be great. Thank you! -Corby-
hello it seems lack of c# skills is getting the better of me here...iv been trying to get this to work for hours now without success. I have just started working in c# so i am a beginner :) all i want to do it query the database, check to see if a title exists, if yes then populate textbox saying 'title in use' but if the title doesnt exists then continue executing rest of code to add the title. You'll notice iv tried to use string variables and sqlDataAdapter but i cant get these to work either...please help so far i have this that keeps giving me the error that my button click is undefined: protected void bookButton_Click(object sender, EventArgs e){ //string title;try{SqlConnection conn1 = new SqlConnection(); conn1.ConnectionString = "Data Source=Gemma-PC\SQLEXPRESS;" +"Initial Catalog=SoSym;" + "Integrated Security=SSPI;";SqlCommand findTitle = new SqlCommand("SELECT title FROM Publication WHERE title='" + titleTextBox.Text + "';", conn1);
conn1.Open(); findTitle.ExecuteNonQuery(); /* DataSet myDataSetTitle = new DataSet("PublicationTitle"); myDataSetTitle.Clear(); myDataAdapterTitle.Fill(myDataSetTitle);//myDataSet contains results from above SELECT statement title = myDataSetTitle.Tables[0].Rows[0]["title"].ToString();*/ }catch(Exception ex) {TitleInvalidMessage.Text = "Title Not Accepted: This title is already in use by another publication" +ex.Message; } //title does not exist in table so continue and add to database //rest of code here
While migrating Report services in SQL Server 2005 to 2014, I am trying to restore the Encryption Key in RS Configuration Manager in2014. But I cannot click the 'Restore' button in RS Configuration Manager. So if I should be grant more right to do so or any other action?
I am configuring log shipping. On the secondary server, I already restored the DB.From the primary server, I was following all the instructions on how to. Now this is the problem. I click on ADD button to connect to the secondary server. I put in the IPInstanceName and the DB. I also chose option 3 (No, the secondary database is initialized), clicked OK after all the option, now getting this error.
I've got a SQL Reporting Server 2000 SP2 report that takes 3 parameters. FromDT, ToDT, and LocationCD. The first two parameters are free form text fields that expect a date. The last one is a drop down box. For some reason, when I'm viewing the report through the standard reports folder on the report server I have to click the "View Report" button two times to get the report to render. Clicking it just once, doesn't seem to do anything. The report is a line graph.
There are default values in the FromDT and ToDT parameter fields.
Anyone have any ideas what would be causing the need for the second click?
I am novice to SQL reporting services. I have created a report using SSRS. In this report I would like to show a column value as button and wants to execute vbscript code on click. Or at least execute vbscript code on click of that field (button is just an option!) The code will launch another application (exe file or else)
I want to update two tables in one page. So I created two FormView bound on two SqlDataSource controls, and I create a Update button on the bottom of page. And I writen some codes as below: btnUpate_Click(object sender, EventArgs e){ sqlDataSource1.Update(); sqlDateSource2.Update();} But, the records haven't updated. In SqlDataSource2_Updating() function, I found all the parameters is null. So, how to modify my code to do it.
<!-- Trying to create a GridView Survey form: Hi [User] Do you have these assets? [Gridview] Tag Number Response 123 [Yes ] [No] [Comments textbox] 234 [Yes ] [No] [Comments textbox]
Goal: The desire is for the user to click Yes or No and have the database updated with the user's name, date, response and any comments.
So far, I have created SqlDataSource with Select and Update commands, created the gridview and response buttons, setup the RowCommand and On_Updating Functions.
Problems:1) If I call the update() function for SqlDataSource1 and misuse the Defaultvalue parameters to run the sql, no update is posted to the database.
2) If I use the On_Update function to set the parameter values, I get "Data type mismatch in criteria expression." (Additionally, the On_Update function runs twice which I don't understand)Can anyone tell me what/why? (and how to fix it?)Sorry for the deluge, but here is the code: -->
<%@ Page Language="VB" %> <html> <head id="Head1" runat="server"> <title>Asset Survey</title> </head> <SCRIPT runat="server"> Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting e.Command.Parameters("Name1").Value = User.Identity.Name End Sub
Protected Sub SqlDataSource1_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles SqlDataSource1.Updating 'For some reason, this function executes twice '2nd execution gets error: "Data type mismatch in criteria expression." 'e.Command.Parameters("PrimaryKey1").Value = intPrimaryKey 'e.Command.Parameters("Responder1").Value = strUser 'e.Command.Parameters("ResponseDate1").Value = dtModDate 'e.Command.Parameters("Response1").Value = strResponse 'e.Command.Parameters("ResponseComments1").Value = strComments End Sub
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) _ Handles GridView1.RowCommand Dim GridRow1 As Integer = Convert.ToInt32(e.CommandArgument) If e.CommandName = "UpdateYes" Then 'code here to disable buttons and textbox '...
SqlDataSource1.UpdateParameters("Response1").DefaultValue = "Yes" End If
If e.CommandName = "UpdateNo" Then 'code here to disable buttons and textbox '...
SqlDataSource1.UpdateParameters("Response1").DefaultValue = "No" End If
'if I use the SqlDataSource1_Updating function, I get the mismatch error 'but if I (mis)use the DefaultValue parameter, no update occurs. SqlDataSource1.UpdateParameters("ResponseComments1").DefaultValue = _
SqlDataSource1.Update() 'Error Here if I use on_updating: "Data type mismatch in criteria expression." Catch except As Exception ' Handle the Exception. End Try End Sub
</SCRIPT> <body> <form id="formInv" runat="server"> <div> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:LocalTestMDB %>" ProviderName="<%$ ConnectionStrings:LocalTestMDB.ProviderName %>" SelectCommand="SELECT [PrimaryKey], [Name], [AssetTag], [Response], [Responder], [ResponseDate],[ResponseComments] FROM [Tablename] WHERE ([Name] = ?) ORDER BY [Login Name], [AssetTag]" UpdateCommand="Update [Tablename] SET [Response]=@Response1, [Responder]=@Responder1, [ResponseDate]=ResponseDate1, [ResponseComments]=ResponseComments1 WHERE [PrimaryKey]=@PrimaryKey1" OnSelecting="SqlDataSource1_Selecting" OnUpdating="SqlDataSource1_Updating"> <SelectParameters>
Hello All I have had asked the same question in another post, i didnt get answer to it i might have had asked it wrongfully
Soo the question is: When creating a SQLDataSource in the wizard you get to the pont where you select the option . It says that by using this datasource you can select to update delete and insert. So my question is if i am creating a select statement to reterieve the data from the Table, then what does it do it do if my intention is to only reterie the data. Or what is the other way that it could be helpful to me ??
thanks all I hope it make sence, if not I wrill write another post to bring step by step info into it.
Hi, I've got a gridview that displays some (but not all) columns from a sql database table. One of the columns that is NOT displayed is the table's primary key column. I'm putting together this row updating sub based on an article I found on the 'Net. Here's the code I've added for the GridView's edit routine (based on the article):Protected Sub gvPersonnelType_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvPersonnelType.RowEditing gvPersonnelType.EditIndex = e.NewEditIndex gvPersonnelTypeBindData() End Sub
Protected Sub gvPersonnelType_RowCancellingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs) gvPersonnelType.EditIndex = -1 gvPersonnelTypeBindData() End Sub
Protected Sub gvPersonnelType_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) 'Dim PersonnelTypeID As Integer'This is not displayed in the gridview, but is the primary key in the database Dim LaborForceTypeID As Integer Dim DefaultPayRate, DefaultPieceRate, Rebill As Decimal'These are money datatype in the database Dim DefaultAdminCostPercent, MarkUp As Double 'These are float datatype in the database'Don't know if the following lines properly "capture" the values in the textboxes LaborForceTypeID = Integer.Parse(gvPersonnelType.Rows(e.RowIndex).Cells(0).Text) DefaultPayRate = CType(gvPersonnelType.Rows(e.RowIndex).Cells(1).Controls(0), TextBox).Text DefaultPieceRate = CType(gvPersonnelType.Rows(e.RowIndex).Cells(2).Controls(0), TextBox).Text DefaultAdminCostPercent = CType(gvPersonnelType.Rows(e.RowIndex).Cells(3).Controls(0), TextBox).Text Rebill = CType(gvPersonnelType.Rows(e.RowIndex).Cells(4).Controls(0), TextBox).Text MarkUp = CType(gvPersonnelType.Rows(e.RowIndex).Cells(5).Controls(0), TextBox).Text
Dim gvSqlConn = New SqlConnection("DATABASECONNECTION")
gvSqlConn.open() Dim UpdatePersonnelTypeCmd As New SqlCommand("UPDATE rsrc_PersonnelType SET LaborForceTypeID = @LaborForceTypeID, " & _ "DefaultPayRate = @DefaultPayRate, DefaultPieceRate = @DefaultPieceRate, " & _ "DefaultAdminCostPercent = @DefaultAdminCostPercent, Rebill = @Rebill, Markup = @Markup", gvSqlConn)
'Sql doesn't know what row to update: NEED WHERE STATEMENT!!!
End Sub As you can see, I've added some notes in the RowUpdating sub. I don't understand how to use the PersonnelTypeID (the database table's primary key) for the WHERE clause to update the correct row in the database. As for the GridView itself, it's populated from the code-behind as well (as you can see from the call to "gvPersonnelTypeBindData()") and the SELECT statement used to populate the gridview doesn't use the PersonnelTypeID column either. I'd appreciate it if someone could point me in the right direction to get this RowUpdating sub working. Thanks!
Hi, I am trying to build a website in C# for a university project, and am having trouble updating a table from the code (at which I'm not too hot on writing). I can manage to get the SQL syntax to work in SQL Server 2005, but when I transfer it to the Visual Web Developer page it doesn't update. Would anyone be able to kindly point out where I am going wrong? My code (apologies for the amount) is;protected void CalculateEmissionsAndTotal() { //Create the ConnectionSqlConnection sqlConn = new SqlConnection("server=Acer-Laptop\SQLEXPRESS; database=NeuCar; Trusted_Connection=true"); //Open the connection sqlConn.Open(); //Create the Command, passing in the SQL statement and the ConnectionString queryString = "DECLARE @Today DATETIME SELECT @Today = Current_Timestamp Declare @TotalCharge int DECLARE @EmissionsUrban int DECLARE @EmissionsCountry int SELECT @TotalCharge = ((MemberPayment.MileageUrban * Vehicle.EmissionsPerGramUrban) * 0.05) + ((MemberPayment.MileageCountry * Vehicle.EmissionsPerGramUrban) * 0.05) FROM [NeuCar].[dbo].[MemberPayment] JOIN [NeuCar].[dbo].[Vehicle] ON MemberPayment.Registration = Vehicle.Registration JOIN [NeuCar].[dbo].[Member] ON Vehicle.UserName = Member.UserName WHERE (Member.UserName = @myUserName) AND (MemberPayment.PaymentDate >= DATEADD(dd,-(DAY(DATEADD(mm,-1,@Today))-1),DATEADD(mm,0,@Today))) SELECT @EmissionsUrban = ((MemberPayment.MileageUrban * Vehicle.EmissionsPerGramUrban) * 0.05) FROM [NeuCar].[dbo].[MemberPayment] JOIN [NeuCar].[dbo].[Vehicle] ON MemberPayment.Registration = Vehicle.Registration JOIN [NeuCar].[dbo].[Member] ON Vehicle.UserName = Member.UserName WHERE (Member.UserName = @myUserName) AND (MemberPayment.PaymentDate >= DATEADD(dd,-(DAY(DATEADD(mm,-1,@Today))-1),DATEADD(mm,0,@Today))) SELECT @EmissionsCountry = ((MemberPayment.MileageCountry * Vehicle.EmissionsPerGramCountry) * 0.05) FROM [NeuCar].[dbo].[MemberPayment] JOIN [NeuCar].[dbo].[Vehicle] ON MemberPayment.Registration = Vehicle.Registration JOIN [NeuCar].[dbo].[Member] ON Vehicle.UserName = Member.UserName WHERE (Member.UserName = @myUserName) AND (MemberPayment.PaymentDate >= DATEADD(dd,-(DAY(DATEADD(mm,-1,@Today))-1),DATEADD(mm,0,@Today))) UPDATE MemberPayment SET TotalCharge = @TotalCharge, EmissionsUrban = @EmissionsUrban, EmissionsCountry = @EmissionsCountry WHERE (Registration = @myRegistration); "; SqlCommand cmd = new SqlCommand(queryString, sqlConn);cmd.Parameters.Add(new SqlParameter("@myUserName", Session["sUserName"])); cmd.Parameters.Add(new SqlParameter("@myRegistration", Session["sRegistration"]));MileageLabel.Text = "*Update complete"; //Close the connection sqlConn.Close(); } I would be very grateful if anybody could help, Kind regards, Chima