Link to home
Start Free TrialLog in
Avatar of mgit
mgit

asked on

Capture Return Value from the SPoc when using FormView

I'm inserting data using FormView, I use SPOC in Insert statement. Spoc has a return value of -1 if the item already exists. How do I capture that returned item and display message to the user?
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

can you clarify "how" the procedure returns that value?
via return value, output parameter or select ?

can you show use your current code to run the procedure? we can then make the adjustments...
Hi, if you're using a return value this code should do the trick:

http://aspnet.4guysfromrolla.com/articles/062905-1.aspx
Dim myConnection as New SqlConnection(connString)
myConnection.Open()
 
Dim myCommand as New SqlCommand("store_GetInventoryWithAveragePrice", myConnection)
myCommand.CommandType = CommandType.StoredProcedure
 
'Create a SqlParameter object to hold the output parameter value
Dim retValParam as New SqlParameter("@RETURN_VALUE", SqlDbType.Int)
 
'IMPORTANT - must set Direction as ReturnValue
retValParam.Direction = ParameterDirection.ReturnValue
 
'Finally, add the parameter to the Command's Parameters collection
myCommand.Parameters.Add(retValParam)
 
'Call the sproc...
Dim reader as SqlDataReader = myCommand.ExecuteReader()
 
'Now you can grab the output parameter's value...
Dim retValParam as Integer = Convert.ToInt32(retValParam.Value)

Open in new window

Avatar of mgit
mgit

ASKER

SP uses return value.
I don't have code to capture this return value.
I use InsertCommand of sqlDataSource to call the SP.
Code is working but the returned value is not captured because there is no code to capture it.
In that case you need to use the InsertParameters collection:
Dim retValParam as New SqlParameter("@RETURN_VALUE", SqlDbType.Int)
retValParam.Direction = ParameterDirection.ReturnValue
myDataSource.InsertParameters.Add(retValParam)
 
Dim retValParam as Integer = Convert.ToInt32(retValParam.Value)

Open in new window

Avatar of mgit

ASKER

This is what I did but is not working I'm getting an error:

Compiler Error Message: BC30188: Declaration expected.

Source Error:

Line 11:    
Line 12:    Dim retValParam as New SqlParameter("@RETURN_VALUE", SqlDbType.Int)
Line 13: retValParam.Direction = ParameterDirection.ReturnValue
Line 14: sqlDataSource1.InsertParameters.Add(retValParam)
Line 15:  
 


<script runat="server">
    
    Sub Button_Clear( s As Object, e As EventArgs)
        Response.Redirect("edit_manager.aspx")
    End Sub
    
   Dim retValParam as New SqlParameter("@RETURN_VALUE", SqlDbType.Int)
retValParam.Direction = ParameterDirection.ReturnValue
sqlDataSource1.InsertParameters.Add(retValParam)
 
Dim retValParam as Integer = Convert.ToInt32(retValParam.Value)
If retValParm = -1 Then
                lblMessage.Text = "This Account already exists - please provide a new ID!"
            Else
                lblMessage.Text = "Done"
            End If
 
    
</script>
 
<asp:TableRow ID="spacer" runat="server">
<asp:TableCell Height="50px" ColumnSpan="2" runat="server" >
<asp:Label CssClass="error_label" 
  ID="lblMessage"
  EnableViewState="False" 
  Runat="Server" />
 
</asp:TableCell></asp:TableRow>
    
  
  <asp:TableRow Width="600px" HorizontalAlign="Center" runat="server">
  <asp:TableCell ColumnSpan="2" BackColor="White" runat="server">
  <asp:FormView runat="server" 
  ID="frmMgr" 
  DataSourceID="sqlDataSource1" 
  AllowPaging="true" DataKeyNames="mgr_email" 
  PagerSettings-Mode="NextPreviousFirstLast" PagerStyle-CssClass="pager">
  <InsertItemTemplate>
  
  <asp:Label Width="150" ID="lblMgr_Name" Text="Manager Name:" AssociatedControlID="txtMgr_Name" runat="server"></asp:Label>
  <asp:TextBox Width="230" ID="txtMgr_Name" Text='<%# Bind("mgr_name") %>' runat="server"></asp:TextBox><br />
 
  <asp:Label Width="150" ID="lblMgr_Email" Text="Manager Email:" AssociatedControlID="txtMgr_Email" runat="server"></asp:Label>
  <asp:TextBox Width="230" ID="txtMgr_Email" Text='<%# Bind("mgr_email") %>' runat="server"></asp:TextBox><br />
  
  <asp:Label Width="150" ID="lblMgr_Password" Text="Manager Password:" AssociatedControlID="txtMgr_Password" runat="server"></asp:Label>
  <asp:TextBox Width="230" ID="txtMgr_Password" Text='<%# Bind("mgr_password") %>' runat="server"></asp:TextBox><br />
  
  <asp:Button ID="lnkInsert" Text="Insert" CommandName="Insert" runat="server"></asp:Button>
  <asp:Button ID="lnkCancel" Text="Cancel" CommandName="Cancel" runat="server"></asp:Button>
  
  </InsertItemTemplate>
  
  
  </asp:FormView>
  
 <asp:SqlDataSource runat="server" 
 ID="sqlDataSource1" ConnectionString="<%$ connectionstrings:conString %>" InsertCommandType="StoredProcedure"  
  SelectCommand="Select mgr_name,mgr_email,mgr_password from mgr_login where id > 1 order by mgr_name asc"
  UpdateCommand="update mgr_login set mgr_name=@mgr_name,mgr_email=@mgr_email,mgr_password=@mgr_password where mgr_email=@mgr_email"
  DeleteCommand="delete mgr_login where mgr_email=@old_mgr_email" 
  InsertCommand="New_Manager" 
  OldValuesParameterFormatString="old_{0}" >
  
  </asp:SqlDataSource>
  
  </asp:TableCell>
  </asp:TableRow>
  <asp:TableRow ID="TableRow1" runat="server">
<asp:TableCell Height="50px" ColumnSpan="2" runat="server" ></asp:TableCell></asp:TableRow>
  
</asp:Table>
 
 
</form>

Open in new window

You're declaring the code outside a method, the first three lines should be in the Page_Load event, and the one to obtain the value should be after you execute the InsertCommand. Looking at your code is not very clear to me when exactly are you calling it.
Avatar of mgit

ASKER

Joe

My Insert Command is part of my <asp:SQLdataSource> as usual I'm lost:
below is almost entire page, it includes Insert and Edit  Tamplates.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Page Language="VB" %>
 
<script runat="server">
    
    Sub Button_Clear( s As Object, e As EventArgs)
        Response.Redirect("edit_manager.aspx")
    End Sub
   
   Sub Page_Load(s as object, e as eventargs)
   Dim retValParam as New SqlParameter("@RETURN_VALUE", SqlDbType.Int)
retValParam.Direction = ParameterDirection.ReturnValue
sqlDataSource1.InsertParameters.Add(retValParam)
 
Dim retValParam as Integer = Convert.ToInt32(retValParam.Value)
If retValParm = -1 Then
                lblMessage.Text = "This Account already exists - please provide a new ID!"
            Else
                lblMessage.Text = "Done"
            End If
end sub
    
</script>
 
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head><title>Manager Management</title>
<link rel="stylesheet" type="text/css" href="../style.css"/>
</head>
<body runat="server" >
<form runat="server" id="Form1">
<asp:Table CssClass="Main_Table" ID="Table1" Width="600" HorizontalAlign="Center" runat="server" Height="212px">
<asp:TableRow runat="server" >
<asp:TableCell Width="300px" HorizontalAlign="Left" runat="server" >
<img src="../images/bsa.gif" alt="logo" width="271" height="64" />
</asp:TableCell>
<asp:TableCell Width="300px" CssClass="menu_text" runat="server">
<a href="../Default.aspx"> HOME </a>
<a href="sign_out.aspx">SIGN OUT</a>
</asp:TableCell>
</asp:TableRow>
 
<asp:TableRow ID="spacer" runat="server">
<asp:TableCell Height="50px" ColumnSpan="2" runat="server" >
<asp:Label CssClass="error_label" 
  ID="lblMessage"
  EnableViewState="False" 
  Runat="Server" />
 
</asp:TableCell></asp:TableRow>
    
  
  <asp:TableRow Width="600px" HorizontalAlign="Center" runat="server">
  <asp:TableCell ColumnSpan="2" BackColor="White" runat="server">
  <asp:FormView runat="server" 
  ID="frmMgr" 
  DataSourceID="sqlDataSource1" 
  AllowPaging="true" DataKeyNames="mgr_email" 
  PagerSettings-Mode="NextPreviousFirstLast" PagerStyle-CssClass="pager">
  
  <HeaderTemplate>
  <h2>Manager Details:</h2>
  </HeaderTemplate>
  
  <ItemTemplate>
  <asp:Table ID="tblItem_Template" runat="server" HorizontalAlign="Center">
  <asp:TableRow>
  <asp:TableCell Width="150">
  Manager Name:
  </asp:TableCell>
  <asp:TableCell  Width="230">
  <%# Eval("mgr_name") %>
  </asp:TableCell>
  </asp:TableRow>
  <asp:TableRow>
  <asp:TableCell>
  Manager Email:
  </asp:TableCell>
  <asp:TableCell>
  <%# Eval("mgr_email") %>
  </asp:TableCell>
  </asp:TableRow>
  <asp:TableRow>
  <asp:TableCell>
  Manager Password:
  </asp:TableCell>
  <asp:TableCell>
  <%# Eval("mgr_password") %>
  </asp:TableCell>
  </asp:TableRow>
  <asp:TableRow>
  <asp:TableCell ColumnSpan="2">
  <asp:Button ID="lnkNew" Text="New" CommandName="New" runat="Server"></asp:Button>
  <asp:Button ID="lnkEdit" Text="Edit" CommandName="Edit" runat="server"></asp:Button>
  <asp:Button ID="lnkDelete" Text="Delete" CommandName="Delete" OnClientClick="return confirm('Are your sure?');" runat="server"></asp:Button>
  </asp:TableCell>
  </asp:TableRow>
  </asp:Table>
  </ItemTemplate>
  
  <InsertItemTemplate>
  
  <asp:Label Width="150" ID="lblMgr_Name" Text="Manager Name:" AssociatedControlID="txtMgr_Name" runat="server"></asp:Label>
  <asp:TextBox Width="230" ID="txtMgr_Name" Text='<%# Bind("mgr_name") %>' runat="server"></asp:TextBox><br />
 
  <asp:Label Width="150" ID="lblMgr_Email" Text="Manager Email:" AssociatedControlID="txtMgr_Email" runat="server"></asp:Label>
  <asp:TextBox Width="230" ID="txtMgr_Email" Text='<%# Bind("mgr_email") %>' runat="server"></asp:TextBox><br />
  
  <asp:Label Width="150" ID="lblMgr_Password" Text="Manager Password:" AssociatedControlID="txtMgr_Password" runat="server"></asp:Label>
  <asp:TextBox Width="230" ID="txtMgr_Password" Text='<%# Bind("mgr_password") %>' runat="server"></asp:TextBox><br />
  
  <asp:Button ID="lnkInsert" Text="Insert" CommandName="Insert" runat="server"></asp:Button>
  <asp:Button ID="lnkCancel" Text="Cancel" CommandName="Cancel" runat="server"></asp:Button>
  
  </InsertItemTemplate>
  
  <EditItemTemplate>
  <asp:Label Width="150" ID="lblMgr_Name" Text="Manager Name:" AssociatedControlID="txtMgr_Name" runat="server"></asp:Label>
  <asp:TextBox Width="230" ID="txtMgr_Name" Text='<%# Bind("mgr_name") %>' runat="server"></asp:TextBox><br />
 
  <asp:Label Width="150" ID="lblMgr_Email" Text="Manager Email:" AssociatedControlID="txtMgr_Email" runat="server"></asp:Label>
  <asp:TextBox Width="230" ID="txtMgr_Email" Text='<%# Bind("mgr_email") %>' runat="server"></asp:TextBox><br />
  
  <asp:Label Width="150" ID="lblMgr_Password" Text="Manager Password:" AssociatedControlID="txtMgr_Password" runat="server"></asp:Label>
  <asp:TextBox Width="230" ID="txtMgr_Password" Text='<%# Bind("mgr_password") %>' runat="server"></asp:TextBox><br />
    
  <asp:Button ID="lnkUpdate" Text="Update" CommandName="Update" runat="server"></asp:Button>
  <asp:Button ID="lnkCancel" Text="Cancel" CommandName="Cancel" runat="server"></asp:Button>
  
  </EditItemTemplate>
  
  </asp:FormView>
  
 <asp:SqlDataSource runat="server" 
 ID="sqlDataSource1" ConnectionString="<%$ connectionstrings:conString %>" InsertCommandType="StoredProcedure"  
  SelectCommand="Select mgr_name,mgr_email,mgr_password from mgr_login where id > 1 order by mgr_name asc"
  UpdateCommand="update mgr_login set mgr_name=@mgr_name,mgr_email=@mgr_email,mgr_password=@mgr_password where mgr_email=@mgr_email"
  DeleteCommand="delete mgr_login where mgr_email=@old_mgr_email" 
  InsertCommand="New_Manager" 
  OldValuesParameterFormatString="old_{0}" >
  
  </asp:SqlDataSource>
  
  </asp:TableCell>
  </asp:TableRow>
  <asp:TableRow ID="TableRow1" runat="server">
<asp:TableCell Height="50px" ColumnSpan="2" runat="server" ></asp:TableCell></asp:TableRow>
  
</asp:Table>
 
 
</form>
</body>
</html>

Open in new window

Sorry seems like you cannot use InsertParameters the same way as a SqlParameter, I've modified your code to use a SqlCommand for the insert of data. Keep in mind that you have to declared the parameters the same way they are declared in your stored procedure. I've only change the part with the code. Let me know how it works out.
<script runat="server">
 
  Sub Button_Clear(ByVal s As Object, ByVal e As EventArgs)
    Response.Redirect("edit_manager.aspx")
  End Sub
 
  Protected Sub lnkInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim conn As New SqlConnection(sqlDataSource1.ConnectionString)
    Using (conn)
      Dim cmd As New SqlCommand("New_Manager", conn)
      Using (cmd)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.Add(New SqlParameter("txtMgr_Name", SqlDbType.VarChar, 200))
        cmd.Parameters.Add(New SqlParameter("txtMgr_Email", SqlDbType.VarChar, 200))
        cmd.Parameters.Add(New SqlParameter("txtMgr_Password", SqlDbType.VarChar, 200))
        Dim retValParam As New SqlParameter("@RETURN_VALUE", SqlDbType.Int)
        retValParam.Direction = ParameterDirection.ReturnValue
        cmd.Parameters.Add(retValParam)
        cmd.ExecuteNonQuery()
 
        Dim valParam As Integer = Convert.ToInt32(retValParam.Value)
        If valParam = -1 Then
          lblMessage.Text = "This Account already exists - please provide a new ID!"
        Else
          lblMessage.Text = "Done"
        End If
      End Using
    End Using
  End Sub
</script>

Open in new window

Also added the onclick event to the lnkInsert button
<asp:Button ID="lnkInsert" Text="Insert" CommandName="Insert" runat="server" OnClick="lnkInsert_Click"></asp:Button>

Open in new window

Avatar of mgit

ASKER

I've tried it couple of different ways.
I'm not getitng any errors but I'm not getting message about records existing.
here is my SP
CREATE PROCEDURE new_manager
@mgr_name char(20),
@mgr_email char(50),
@mgr_password char(20)

AS
 if exists( select mgr_email from mgr_login where mgr_email=@mgr_email)
return -1
else

Insert into mgr_login (mgr_name, mgr_email, mgr_password) Values
                (@mgr_name, @mgr_email, @mgr_password)
GO

When I try to insert a duplicate records it doesn't insert it but also doesn't return messeage about records existing.
When you run the SP on its own, I mean directly in SQL Server,  does it return the -1 as expected?
Avatar of mgit

ASKER

I'm getting an error now:

Exception Details: System.InvalidOperationException: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.

Source Error:


Line 23:         retValParam.Direction = ParameterDirection.ReturnValue
Line 24:         cmd.Parameters.Add(retValParam)
Line 25:         cmd.ExecuteNonQuery()
Line 26:  
Line 27:         Dim valParam As Integer = Convert.ToInt32(retValParam.Value)
 
sorry forgot the open statement, add this after the first using:
conn.Open()

Open in new window

Avatar of mgit

ASKER

still no luck.
here is the error:

Procedure 'new_manager' expects parameter '@mgr_name', which was not supplied.
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: Procedure 'new_manager' expects parameter '@mgr_name', which was not supplied.

Source Error:
Line 24:         retValParam.Direction = ParameterDirection.ReturnValue
Line 25:         cmd.Parameters.Add(retValParam)
Line 26:         cmd.ExecuteNonQuery()
Line 27:  
Line 28:         Dim valParam As Integer = Convert.ToInt32(retValParam.Value)

I've edidted the Sub to include @mgr_name etc as SP requires, I get the above error.
when I do this:
cmd.Parameters.Add(New SqlParameter("@mgr_name", txtMgr_Name, SqlDbType.VarChar, 200))

I get an error about txtMgr_Name is not declared.

Joe is it possible to get this done using <parameter> in the asp:sqlDataSource?
it has input and output parameters maybe that would be easier?
I'm not sure over my head  -
 
One more try, I think this should be it:
  Protected Sub lnkInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim conn As New SqlConnection(sqlDataSource1.ConnectionString)
    Using (conn)
      conn.Open()
      Dim cmd As New SqlCommand("New_Manager", conn)
      Using (cmd)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.Add(New SqlParameter("@mgr_name", SqlDbType.Char, 20))
        cmd.Parameters(0).Value = CType(frmMgr.FindControl("txtMgr_Name"), TextBox).Text
        cmd.Parameters.Add(New SqlParameter("@mgr_email", SqlDbType.Char, 50))
        cmd.Parameters(1).Value = CType(frmMgr.FindControl("txtMgr_Email"), TextBox).Text
        cmd.Parameters.Add(New SqlParameter("@mgr_password", SqlDbType.Char, 20))
        cmd.Parameters(2).Value = CType(frmMgr.FindControl("txtMgr_Password"), TextBox).Text
        Dim retValParam As New SqlParameter("@RETURN_VALUE", SqlDbType.Int)
        retValParam.Direction = ParameterDirection.ReturnValue
        cmd.Parameters.Add(retValParam)
        cmd.ExecuteNonQuery()
 
        Dim valParam As Integer = Convert.ToInt32(retValParam.Value)
        If valParam = -1 Then
          lblMessage.Text = "This Account already exists - please provide a new ID!"
        Else
          lblMessage.Text = "Done"
        End If
      End Using
    End Using
  End Sub

Open in new window

Avatar of mgit

ASKER

it still doesn't like line 20:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 18:         cmd.CommandType = CommandType.StoredProcedure
Line 19:         cmd.Parameters.Add(New SqlParameter("@mgr_name", SqlDbType.Char, 20))
Line 20:         cmd.Parameters(0).Value = CType(frmMgr.FindControl("txtMgr_Name"), TextBox).Text
Line 21:         cmd.Parameters.Add(New SqlParameter("@mgr_email", SqlDbType.Char, 50))
Line 22:         cmd.Parameters(1).Value = CType(frmMgr.FindControl("txtMgr_Email"), TextBox).Text
 

Avatar of mgit

ASKER

Joe

Please look at this code and see if that could be used:


Protected Sub myDataSource_Inserted(ByVal sender As Object, _
      ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) _
      Handles myDataSource.Inserted
 
    ' Get the return value from the stored procedure. 
    Dim id As Integer = Convert.ToInt32(e.Command.Parameters("@returnValue").Value)
End Sub
 
in combination with the following DataSource markup:
 
<asp:SqlDataSource ID="myDataSource" runat="server" 
       InsertCommand="SomeSproc InsertCommandType="StoredProcedure"
  <InsertParameters>
    <asp:Parameter Name="returnValue" Type="Int32" Direction="ReturnValue" />
    <asp:Parameter Name="YourField1" Type="Int32" />
    <asp:Parameter Name="YourField2" Type="String" />
  </InsertParameters>
</asp:SqlDataSource>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Oliver Amaya
Oliver Amaya
Flag of Venezuela, Bolivarian Republic of image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mgit

ASKER

Joe

It did work - appreciate your help a lot. I've got some more stuff that I'll struggle with - my email address is mark_at_badapplesonline.com if you can please email me your contact info.
Don't worry about it, I'll contact you via email, glad I could help.