Deleting from SQL detailsView - asp.net

Hey I am just learning to how to use asp.net and I am trying to use the grid view to display information and details view edit/delete the information from the database. Right now I can edit and update the information in the database but I also want it to delete and something is not working for me. I set up an exception and when I select the item and press delete it pops up my exception that another user has deleted the item when it hasn't. Im not really sure what i have done wrong, to me it looks like it should work.
Here is the code for the delete command and parameters from the details view
DeleteCommand="DELETE FROM [Customers]
WHERE [CustomerID] = #original_CustomerID
AND [Name] = #original_Name
AND [Address] = #original_Address
AND [City] = #original_City
AND [State] = #original_State
AND [ZipCode] = #original_ZipCode
AND ([Phone] = #original_Phone
OR [Phone] IS NULL AND #original_Phone IS NULL)
AND ([Email] = #original_Email
OR [Email] IS NULL AND #original_Email IS NULL)"
<DeleteParameters>
<asp:Parameter Name="original_CustomerID" Type="Int32" />
<asp:Parameter Name="original_Name" Type="String" />
<asp:Parameter Name="original_Address" Type="String" />
<asp:Parameter Name="original_City" Type="String" />
<asp:Parameter Name="original_State" Type="String" />
<asp:Parameter Name="original_ZipCode" Type="String" />
<asp:Parameter Name="original_Phone" Type="String" />
<asp:Parameter Name="original_Email" Type="String" />
</DeleteParameters>
and here is the delete functions in the cs file
protected void DetailsView1_ItemDeleted(object sender, DetailsViewDeletedEventArgs e)
{
if (e.Exception != null)
{
lblError.Text = "A database error has occurred.<br /><br />" +
"Message: " + e.Exception.Message;
e.ExceptionHandled = true;
}
else if (e.AffectedRows == 0)
lblError.Text = "Another user may have deleted that customer."
+ "<br />Please try again.";
else
GridView1.DataBind();
}
protected void DetailsView1_ItemDeleting(
object sender, DetailsViewDeleteEventArgs e)
{
e.Values["Name"]
= e.Values["Name"].ToString().Substring(1);
}

Why do you have such a huge query for a delete statement?Have a look how it's done in the MSDN DetailsView example
The CustomerID in your SQL table should be unique so your delete statement should be as simple as:
DeleteCommand="DELETE FROM [Customers] WHERE [CustomerID] = #original_CustomerID"
And only one delete parameter:
<DeleteParameters>
<asp:Parameter Name="original_CustomerID" Type="Int32" />
</DeleteParameters>
One more thing which is quite important is you need to set DataKeyNames="CustomerID" on the DetailsView so that DetailsView1_ItemDeleted knows which row to delete. Hope this helps!

Related

Send e-mail after update statement in ASPX

I'm building for my project work at school a website.
The main idea is that users can report damage or report a non functioning computer.
Then the IT department can give in if they've taken any steps try fixing it and there is also a checkbox if the problem is dealth with. If the checkbox in the formview is checked and updated, there should be sent an automatic e-mail to the original user with a message that the problem is solved. I've done everything and everything works, except for the e-mail part.
Can anybody give me some advice in how I should do this? There is an unique datasource who handeles the update statement.
Yours sincerely;
A.
Here is my code:
<asp:AccessDataSource ID="accAfgehandeld" runat="server"
DataFile="~/App_data/dbMeldingen.mdb"
DeleteCommand="DELETE FROM [tblMeldingen] WHERE [MeldingID] = ?"
InsertCommand="INSERT INTO [tblMeldingen] ([MeldingID], [Afgehandeld], [Categorie]) VALUES (?, ?, ?)"
SelectCommand="SELECT [MeldingID], [Afgehandeld], [Categorie] FROM [tblMeldingen] WHERE ([MeldingID] = ?)"
UpdateCommand="UPDATE [tblMeldingen] SET [Afgehandeld] = true, [Categorie] = ? WHERE [MeldingID] = ?"
OnUpdated="OnDSUpdatedHandler">
<DeleteParameters>
<asp:Parameter Name="MeldingID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="MeldingID" Type="Int32" />
<asp:Parameter Name="Afgehandeld" Type="Boolean" />
<asp:Parameter Name="Categorie" Type="Int32" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="MeldingID" QueryStringField="id" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Categorie" Type="Int32" />
<asp:Parameter Name="MeldingID" Type="Int32" />
</UpdateParameters>
</asp:AccessDataSource>
and my script in the same page:
<%# Control Language="VB" AutoEventWireup="false" CodeFile="meldingendetails.ascx.vb" Inherits="meldingendetails" %>
<script runat="server">
private void OnDSUpdatedHandler(Object sender, e.Updated) {
if (e.AffectedRows > 0)
{
MailMessage mailMessage = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.your-isp.com");
smtpClient.Send(mailMessage);
}
}
</script>
Visual studio gives an error over and over again with my script, even from the void part...
Set OnUpdated-handler
<asp:SqlDataSource
...
UpdateCommand="..."
OnUpdated="OnDSUpdatedHandler">
</asp:SqlDataSource>
and use it to send email
<script runat="server">
private void OnDSUpdatedHandler(Object source, SqlDataSourceStatusEventArgs e) {
if (e.AffectedRows > 0) {
MailMessage mailMessage = new MailMessage();
...
SmtpClient smtpClient = new SmtpClient("smtp.your-isp.com");
smtpClient.Send(mailMessage);
}
}
</script>

ASP.NET UpdateCommand with multiple tables updates

I am using ASP.NET and using a grid with the UpdateCommand to update 2 tables
I have the following but doesn't seem to work as I do not get any errors but it simply does not update. From what you can see, am I on the right track?
UpdateCommand="UPDATE [tbl_ProgDt] SET [Type] = #type, [Identifiction] = #samplePoint WHERE [Seq] = #valID UPDATE [tbl_Prog] SET StoreNum = #storeNum WHERE ID = (SELECT ID FROM [tbl_ProgDt] WHERE [Seq] = #valID " >
<UpdateParameters>
<asp:Parameter Name="type" Type="String" />
<asp:Parameter Name="samplePoint" Type="String" />
<asp:Parameter Name="valID" Type="Int32" />
<asp:Parameter Name="storeNum" Type="Int32" />
<asp:Parameter Name="valID" Type="Int32" />
</UpdateParameters>
If you need to do something like that, it would be better to create a stored procedure and wrap the two update sentences using a database transaction
You need to specify:
UpdateCommandType="StoredProcedure" UpdateCommand="Stored Procedure Name"
In your Stored Procedure, something like this:
BEGIN TRANSACTION;
-- your update sentences
COMMIT TRANSACTION;

Gridview not updating table when column/cell starts with no data

UPDATED: Here is the SP, it doesn't match exactly because of ongoing testing, but you get the jist. Some fields are commented out because of testing....
#tableName Varchar(150),
#new_lang_String nvarchar(max),
-- #lang_String nvarchar(max),
#ID int,
#prev_LangString nvarchar(max) = NULL,
#original_lang_String nvarchar(max) = NULL,
#brief_Descrip nvarchar(max) = NULL,
#submittedBy nvarchar(250) = NULL
AS
/* SET NOCOUNT ON */
DECLARE #lang_String varchar(max);
SET #prev_LangString = #new_lang_String;
DECLARE #submitDate1 DATETIME;
SET #submitDate1 = GETDATE();
DECLARE #sql varchar(max);
SET #lang_String = #original_lang_String;
BEGIN
SET #sql = 'UPDATE ' + #tableName + ' SET [lang_String] = ''' + COALESCE(#lang_String, NULL) + ''', [date_Changed] = ''' + convert(varchar(20), #submitDate1) + ''', [prev_LangString] = ''' + COALESCE(#prev_LangString, NULL) + ''', [brief_Descrip] = ''' + COALESCE(#brief_Descrip, NULL) + ''', [submittedBy] = ''' + #submittedBy + '''
WHERE (ID = ' + CAST(#ID as nvarchar(10)) + '); '
EXECUTE(#sql);
END
RETURN
As you can probably tell in the code I have been struggling with handling the Null in some of the fields as well. Hence the default values inteh update parameters of = " " on some fields.
I am using a gridview to display information that is retrieved from a table in a SQL Express DB. When the user clicks EDIT, and enters information, I am trying to update the table with a STORED PROCEDURE called from the Gridview. See aspx code below.
The issue is that the column which is being edited will not update the DB table unless it had previously had data stored in it, as in the cell in the column IS NOT Null. No errors.
Since most cells in this column are Null to begin with, no data is getting updated. No errors, just nothing written to the table. If the table previously had data within the column cell in question it can be succesfully edited and updated.
Gridview from ASPX Page....
<asp:BoundField DataField="lang_String" HeaderText="Foreign Text" SortExpression="lang_String">
<ControlStyle Width="400px"/>
</asp:BoundField>
Update Command on Gridview calls SP, which works, provided column/cell already had data...
UpdateCommand="EXEC usp_UpdatePTEdit #tableName, #lang_String=#lang_String, #ID=#original_ID, #prev_LangString=#original_lang_String, #brief_Descrip=#brief_Descrip, #submittedBy=#SubmittedBy">
Parameters passed to UpdateCommand, only using a few...
<UpdateParameters>
<asp:SessionParameter Name="tableName" SessionField="tableName1" />
<asp:SessionParameter Name="submittedBy" SessionField="SubmittedByUser" />
<asp:Parameter Name="data_text" Type="String" />
<asp:Parameter Name="lang_String" Type="String" DefaultValue=" " />
<asp:Parameter Name="date_Changed" Type="DateTime" />
<asp:Parameter Name="prev_LangString" Type="String" DefaultValue=" " />
<asp:Parameter Name="needsTranslation" Type="String" />
<asp:Parameter Name="displayRecord" Type="String" />
<asp:Parameter Name="brief_Descrip" Type="String" DefaultValue=" " />
<asp:Parameter Name="original_ID" Type="Int32" />
<asp:Parameter Name="original_data_text" Type="String" />
<asp:Parameter Name="original_lang_String" Type="String" />
<asp:Parameter Name="original_date_Changed" Type="DateTime" />
<asp:Parameter Name="original_prev_LangString" Type="String" />
<asp:Parameter Name="original_needsTranslation" Type="String" />
<asp:Parameter Name="original_displayRecord" Type="String" />
<asp:Parameter Name="original_brief_Descrip" Type="String" />
<asp:Parameter Name="original_submittedBy" Type="String" />
</UpdateParameters>
Everything works if the cell originally has data, "original_lang_String" but if it has not been populated, I can not use the Edit operation of the Gridview to successfully update the table.
Any help or suggestions would be appreciated.
#prev_LangString=#original_lang_String
Depending on what is in usp_UpdatePTEdit, I bet it's failing because somewhere it's checking for an original value that doesn't exist. NULL is special and equality checks for it fail.
Post the code that is in usp_UpdatePTEdit stored proc for more help.
I think the problem may be with the assignment of the parameters to the column of the same name (#lang_String=#lang_String). I recommend specifying the parameters in the order that they appear in the stored proc and remove the #name= syntax. I think that is just going to get the datasource or grid view confused.
Update
I think that you would be better off changing the UpdateCommand to:
UpdateCommand="usp_UpdatePTEdit"
and adding:
UpdateCommandType="StoredProcedure"
This seems to be a better fit for how the update command is designed to work.

SWL Error Function has too many arguments specified

I am using ASP.NET 3.5 and SQL Server 2008.
I have a SQLDataSource & Gridview. I am trying to update 2 tables at the same time using a stored procedure in SQL.
SQLDatasource is passing 7 parameters.
5 parameters that the stored procedaure needs, Return value & StudentID.
Not sure if the error is in my SQLDatasorce or my stored procedure.
Here's my ASPX Code:
<asp:SqlDataSource ID="sqldsUserLoginNLevels" runat="server"
ConnectionString="<%$ ConnectionStrings:QuizStarConnectionString %>"
SelectCommand="SELECT UserLogins.StudentID, UserLogins.StudentName, UserLogins.UserID,
UserLogins.Password, UserLevels.GrammarStart, UserLevels.GrammarCurrent,
UserLevels.MathStart, UserLevels.MathCurrent
FROM UserLogins
INNER JOIN UserLevels ON UserLogins.StudentID = UserLevels.StudentID"
DeleteCommand="DELETE FROM [UserLogins] WHERE [StudentID] = #original_StudentID"
InsertCommand="INSERT INTO [UserLogins] ([StudentName], [UserID], [Password])
VALUES (#StudentName, #UserID, #Password)"
UpdateCommand="UpdateUserLoginsAndUserLevels"
UpdateCommandType="StoredProcedure" >
<DeleteParameters>
<asp:Parameter Name="original_StudentID" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="StudentName" Type="String" />
<asp:Parameter Name="UserID" Type="String" />
<asp:Parameter Name="Password" Type="String" />
<asp:Parameter Name="GrammarStart" Type="String" />
<asp:Parameter Name="MathStart" Type="String" />
<asp:Parameter Direction="ReturnValue" Name="RETURN_VALUE" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="StudentName" Type="String" />
<asp:Parameter Name="UserID" Type="String" />
<asp:Parameter Name="Password" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
My Stored Procedure is:
ALTER PROCEDURE [dbo].[UpdateUserLoginsAndUserLevels] (
#StudentName VARCHAR(50),
#UserID NCHAR(10),
#Password NCHAR(10),
#GrammarStart NCHAR(10),
#MathStart NCHAR(10))
AS
DECLARE #StudentID INT;
BEGIN Transaction
BEGIN TRY
SELECT * From UserLogins
Where StudentID = #StudentID
UPDATE UserLogins
SET
StudentName= #StudentName,
UserID = #UserID,
Password = #Password
Where StudentID = #StudentID
UPDATE UserLevels
SET
GrammarStart= #GrammarStart,
MathStart = #MathStart
FROM UserLevels
INNER JOIN UserLogins ON UserLogins.StudentID = UserLevels.StudentID
WHERE (UserLevels.StudentID = #StudentID)
END TRY
BEGIN CATCH
DECLARE #ErrorMessage NVARCHAR(4000), #ErrorSeverity INT
-- Assign variables to error-handling functions that
-- capture information for RAISERROR.
SELECT #ErrorMessage = ERROR_MESSAGE(), #ErrorSeverity = ERROR_SEVERITY()
-- Rollback the failed transaction
ROLLBACK;
-- Raise an error: with the original error information.
RAISERROR(#ErrorMessage, #ErrorSeverity, 1);
END CATCH
COMMIT Transaction;
Have't figured how to post code yet. Sorry.
Make sure you are not double adding parameters. Since you are adding them in the aspx page you do not need to add them in your code behind.
For example if your code behind has this in it:
sqldsUserLoginNLevelsUserID.UpdateParameters.Add(new Parameter("UserID ", TypeCode.Int32));
It could explain your error.
If you need to set the value from code behind do it like this:
sqldsUserLoginNLevelsUserID.UpdateParameters["UserID "].DefaultValue = "1";

setting the default value for insert parameters in sql datasource asp.net

i have a datasource, which has an insertparameters, one of which whose type is set to Boolean, but while adding it from code behind insertparameters.defaultvalue always return string.
code behind code:
if (e.CommandName == "InsertNew")
{
TextBox Title = GridView1.FooterRow.FindControl("txtAddTitle") as TextBox;
TextBox Quote = GridView1.FooterRow.FindControl("txtAddQuote") as TextBox;
TextBox QuoteLink = GridView1.FooterRow.FindControl("txtAddQuoteLink") as TextBox;
CheckBox Published = GridView1.FooterRow.FindControl("chkAddBox") as CheckBox;
TextBox PublishedDate = GridView1.FooterRow.FindControl("txtAddPublishedDate") as TextBox;
SqlDataSource1.InsertParameters["Title"].DefaultValue = Title.Text;
SqlDataSource1.InsertParameters["Quote"].DefaultValue = Quote.Text;
SqlDataSource1.InsertParameters["QuoteLink"].DefaultValue = QuoteLink.Text;
SqlDataSource1.InsertParameters["Published"].DefaultValue = Convert.ToString(Published.Checked);
SqlDataSource1.InsertParameters["PublishedDate"].DefaultValue = PublishedDate.Text;
SqlDataSource1.Insert();
}
and aspx code for sql datasource is:
<InsertParameters>
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="Quote" Type="String" />
<asp:Parameter Name="QuoteLink" Type="String" />
<asp:Parameter Name="Published" Type="Boolean" />
<asp:Parameter Name="PublishedDate" Type="DateTime" />
</InsertParameters>
Please reply how should i set the datatype as boolean from code behind.
1: Not sure why you are setting DefaultValue instead of the value
Or
2: Can you try this:
SqlDataSource1.InsertParameters["Published"].DefaultValue = Published.Checked==true?"true":"false";

Resources