Get scope_identity returned value - asp.net

How can i get the scope identity parameter in my vb code. I have this so far....
InsertCommand="INSERT INTO [table_name] ([title], [subtitle], [description], [image1], [image1_caption], [image2], [pdf], [meta_description], [meta_keywords]) VALUES (#title, #subtitle, #description, #image1, #image1_caption, #image2, #pdf, #meta_description, #meta_keywords); SELECT #NewID = SCOPE_IDENTITY()"
<asp:Parameter Direction="Output" Name="NewID" Type="Int32" />
How can i retreive this ID, in the DetailsView1_ItemInserted?
If you need anymore info let me know.
Thanks

Did you try this in the ItemInserted event handler?
Sub EmployeeDetailsSqlDataSource_OnInserted(sender As Object, e As SqlDataSourceStatusEventArgs)
Dim command As System.Data.Common.DbCommand = e.Command
EmployeesDropDownList.DataBind()
EmployeesDropDownList.SelectedValue = _
command.Parameters("#NewID").Value.ToString()
EmployeeDetailsView.DataBind()
End Sub
Not sure if you need Parameter Direction attribute.
Check out this MSDN article, they do exactly what you are attempting.
http://msdn.microsoft.com/en-us/library/xt50s8kz(VS.80).aspx

Related

Can an ASP.Net asp:ControlParameter ControlID be a public shared variable instead of an asp:label?

Can an ASP.Net asp:ControlParameter ControlID be a public shared variable instead of an ASP:label?
We were using an asp:label as a parameter for a DataSource but now want to use a public shared variable instead of the label.
This is the markup of the parameter using the asp:label.
<asp:ControlParameter
ControlID="LabelCheckBoxMonday"
Name="DayOfWeekMonday"
PropertyName="Text"
Type="String" />
We added this public shared variable in the code-behind.
Public Shared blnDayOfWeekMonday As Boolean
We changed the markup for the parameter to this.
<asp:ControlParameter
ControlID="blnDayOfWeekMonday"
Name="DayOfWeekMonday"
PropertyName="Text"
Type="String" />
This is the coding that places values into the variable. The original coding that used to do that for the label is commented out.
Protected Sub ImageButtonInsertDayOfWeekMonday_Click(sender As Object, e As ImageClickEventArgs)
Dim imgTheImageButton As New ImageButton
imgTheImageButton = DetailsView.FindControl("ImageButtonInsertDayOfWeekMonday")
If imgTheImageButton.ImageUrl = "../../Images/checked.png" = True Then
imgTheImageButton.ImageUrl = "../../Images/unchecked.png"
' LabelCheckBoxMonday.Text = False
blnDayOfWeekMonday = False
Else
imgTheImageButton.ImageUrl = "../../Images/checked.png"
' LabelCheckBoxMonday.Text = True
blnDayOfWeekMonday = True
End If
End Sub
All of this is part of the following InsertCommand:
InsertCommand=
"INSERT INTO [TeacherSchedule]
([DayOfWeekMonday],
[DayOfWeekTuesday],
[DayOfWeekWednesday],
[DayOfWeekThursday],
[DayOfWeekFriday],
[DayOfWeekSaturday],
[DayOfWeekSunday],
[StartTime],
[EndTime],
[ClassID],
[TeacherID])
VALUES (#DayOfWeekMonday,
#DayOfWeekTuesday,
#DayOfWeekWednesday,
#DayOfWeekThursday,
#DayOfWeekFriday,
#DayOfWeekSaturday,
#DayOfWeekSunday,
#StartTime,
#EndTime,
#ClassID,
#TeacherID)"
When the web form is running nothing happens after changing it to the public shared variable.
Can you tell me what else I need to do to proceed?
* Update *
Using Marks suggestion I found out how to do an asp:QueryStringParameter but still don't know how to populate it with a value. This is the parameter as an asp:QueryStringParameter
<asp:QueryStringParameter
Name="DayOfWeekMonday"
QueryStringField="QSDayOfWeekMonday" />
How do I populate QSDayOfWeekMonday in the ImageButtonInsertDayOfWeekMonday_Click sub routine?
I tried:
QSDayOfWeekMonday = False
but got a "not declared" error.
* Full markup and code-behind coding *
http://pastebin.com/embed_js.php?i=kye3c2U8
Another option is to use a Parameter as:
<asp:Parameter Name="DateOfWeekMonthly" />
And in code set the DefaultValue property to the value you want to specify, as in:
DataSourceControl1.Parameters["DateOfWeekMonthly"].DefaultValue = someVariable;
This has worked for me.
You could establish this event in the Selecting event that fires; this event fires before the select happens; therefore, you can establish the boolean value. I believe here, you can add it to the collection of values defined in the event argument.
I used this shorter way:
<asp:Parameter Name="DateOfWeekMonthly" Type="Boolean" DefaultValue="true" />
This is also working.

error in nvarchar to date, date not supplied, either problem in onclick event or stored procedure or in gridview

For your information, I am using Visual Studio Professional 2010
Can someone please help me out, I think the #dateFound parameter is not supplied with a value on click event.
I have a gridview populated from stored procedure as given below.
<asp:SqlDataSource id="Sql20"
ConnectionString='<%$ ConnectionStrings:connectionString %>'
SelectCommand="dbo.StoredProcedure2"
Runat="server" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
The storedProcedure2 is as follow which is suppose to show all the data in gridview if #dateFound IS NULL, by default as below
ALTER PROCEDURE dbo.StoredProcedure2
(
#dateFound DATE
)
AS
/* SET NOCOUNT ON */
IF #dateFound IS NULL
BEGIN
SELECT
lc_orders_tb.lc_orderID,
lc_orders_tb.lc_orderSubTotal,
lc_orders_tb.lc_orderTotal,
lc_orders_tb.LRNo,
lc_orders_tb.LRDate,
lc_orders_tb.lc_orderPlacedDate,
lc_orders_tb.LInvoiceLoc,
lc_orderStatus_tb.lc_orderStatusDescrip,
lc_orderStatus_tb.lc_delType,
lc_tb.lc_compName,
lc_tb.lc_addCity,
(SELECT SUM(lc_orderQuantity)
FROM lc_orderQuantity_tb
WHERE
lc_orders_tb.lc_orderID=lc_orderQuantity_tb.lc_OrderID) as lc_orderQuantity
FROM lc_orders_tb
INNER JOIN
lc_tb ON lc_orders_tb.lc_id = lc_tb.lc_id
INNER JOIN
lc_orderStatus_tb ON lc_orders_tb.lc_orderID = lc_orderStatus_tb.lc_orderID
ORDER BY lc_orders_tb.lc_orderPlacedDate DESC
END
ELSE
BEGIN
SELECT
lc_orders_tb.lc_orderID,
lc_orders_tb.lc_orderSubTotal,
lc_orders_tb.lc_orderTotal,
lc_orders_tb.LRNo,
lc_orders_tb.LRDate,
lc_orders_tb.lc_orderPlacedDate,
lc_orders_tb.LInvoiceLoc,
lc_orderStatus_tb.lc_orderStatusDescrip,
lc_orderStatus_tb.lc_delType,
lc_tb.lc_compName,
lc_tb.lc_addCity,
(SELECT SUM(lc_orderQuantity)
FROM lc_orderQuantity_tb
WHERE
lc_orders_tb.lc_orderID = lc_orderQuantity_tb.lc_OrderID) as lc_orderQuantity
FROM lc_orders_tb
INNER JOIN
lc_tb ON lc_orders_tb.lc_id = lc_tb.lc_id
INNER JOIN
lc_orderStatus_tb ON lc_orders_tb.lc_orderID = lc_orderStatus_tb.lc_orderID
WHERE
convert(varchar(10), lc_orders_tb.lc_orderPlacedDate, 103) = #dateFound
ORDER BY lc_orders_tb.lc_orderPlacedDate DESC
END
RETURN
#dateFound will be supplied when clicked on a button click but by default, I mean, when page loads it is not supplied and therefore it should execute the first if statement but it different errors like #dateFound not supplied or error on converting nvarchar to date. The ELSE statement of the SP should get executed if #dateFound supplied from the textbox after clicking on the button. But I cant seem to work out. Please have a look at the click event of the button which is supplying the #dateFound
Protected Sub CustomGV3_onClick(ByVal sender As Object, ByVal e As EventArgs)
Dim connectionString As String =
WebConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand("dbo.StoredProcedure2", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue
("#dateFound", Format(txtBoxDateFrom.Text, "dd/MM/yyyy"))
Using con
con.Open()
cmd.ExecuteReader()
con.Close()
End Using
GridView3.DataBind()
End Sub
Can someone please help me out. Does it seem like I have a totally wrong approach ? Can someone please correct me.
awaiting your kind help plz..
Thanking You
Try changing your stored procedure to use a default value for the #dateFound parameter:
ALTER PROCEDURE dbo.StoredProcedure2
(
#dateFound DATE = NULL
)
AS
I finally got the answer from other forum, it worked by simply changing following in the SP
(
#dateFound DATE = '01/01/1900'
)
The above date is set as default as it will never be going to be in the database against which I will be checking by IF STATEMENT in SP. And in the aspx page to as below.
<SelectParameters>
<asp:ControlParameter ControlID="txtBoxDateFrom"
Name="dateFound" PropertyName="Text"
DbType="Date" DefaultValue="01/01/1900" />
Thanks to all contributor who tried to help me out here..

how to pass a GUID to a select query of SqlDataSource

I have an SqlDataSource with following command:
SELECT * FROM [vw_aspnet_MembershipUsers] WHERE ([UserId] = #UserId)
When I pass simple GUID like "3bd08871-d5d6-4f38-8c8a-29fd6077a719" as a UserId, then nothing gets selected. So what is the correct format for passing the GUID value?
How do I pass a GUID value into an SqlCommand object SQL INSERT statement?
Try putting the value in single quotes.
Had to change the parameter's type from Object to String:
<asp:QueryStringParameter Name="UserID" QueryStringField="UserID" Type="String" />

Return value from SQL 2005 SP returns DBNULL - Where am I going wrong?

This is the SP...
USE [EBDB]
GO
/****** Object: StoredProcedure [dbo].[delete_treatment_category] Script Date: 01/02/2009 15:18:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
RETURNS 0 FOR SUCESS
1 FOR NO DELETE AS HAS ITEMS
2 FOR DELETE ERROR
*/
ALTER PROCEDURE [dbo].[delete_treatment_category]
(
#id INT
)
AS
SET NOCOUNT ON
IF EXISTS
(
SELECT id
FROM dbo.treatment_item
WHERE category_id = #id
)
BEGIN
RETURN 1
END
ELSE
BEGIN
BEGIN TRY
DELETE FROM dbo.treatment_category
WHERE id = #id
END TRY
BEGIN CATCH
RETURN 2
END CATCH
RETURN 0
END
And I'm trying to get the return value using the below code (sqlDataSource & Gridview combo in VB .NET
Protected Sub dsTreatmentCats_Deleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles dsTreatmentCats.Deleted
Select Case CInt(e.Command.Parameters(0).Value)
Case 0
'it worked so no action
lblError.Visible = False
Case 1
lblError.Text = "Unable to delete this category because it still has treatments associated with it."
lblError.Visible = True
Case 2
lblError.Text = "Unable to delete this category due to an unexpected error. Please try again later."
lblError.Visible = True
End Select
End Sub
The problem is that the line CInt(e.Command.Parameters(0).Value) returns a DBNull instead of the return value but only on deletes - this approach works fine with both updates and inserts.
Hopefully I'm just being a bit dense and have missed something obvious - any ideas?
Edit
I'm still having this problem and have tried all of the options below to no avail - I'm surprised no one else has had this problem?
Code for adding parameters:
<asp:SqlDataSource ID="dsTreatmentCats" runat="server"
ConnectionString="<%$ ConnectionStrings:EBDB %>"
DeleteCommand="delete_treatment_category" DeleteCommandType="StoredProcedure"
InsertCommand="add_treatment_category" InsertCommandType="StoredProcedure"
SelectCommand="get_treatment_categories" SelectCommandType="StoredProcedure"
UpdateCommand="update_treatment_category"
UpdateCommandType="StoredProcedure" ProviderName="System.Data.SqlClient">
<DeleteParameters>
<asp:Parameter Direction="ReturnValue" Name="RetVal" Type="Int32" />
<asp:Parameter Name="id" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Direction="ReturnValue" Name="RetVal" Type="Int32" />
<asp:Parameter Name="id" Type="Int32" />
<asp:Parameter Name="name" Type="String" />
<asp:Parameter Name="additional_info" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Direction="ReturnValue" Name="RetVal" Type="Int32" />
<asp:ControlParameter ControlID="txtCat" Name="name" PropertyName="Text"
Type="String" />
<asp:ControlParameter ControlID="txtAddInfo" Name="additional_info"
PropertyName="Text" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
I'm a little late to the game here, but for the sake of people who stumble upon this question...
If you're using ExecuteReader in ADO.Net, the return value will not be populated until you close either the Reader or the underlying connection to the database. (See here)
This will not work:
SqlConnection conn = new SqlConnection(myConnectionString);
SqlCommand cmd = new SqlCommand(mySqlCommand, conn);
// Set up your command and parameters
cmd.Parameters.Add("#Return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// Read your data
}
int resultCount = (int)cmd.Parameters["#Return"].Value;
conn.Close();
return resultCount;
This will:
SqlConnection conn = new SqlConnection(myConnectionString);
SqlCommand cmd = new SqlCommand(mySqlCommand, conn);
// Set up your command and parameters
cmd.Parameters.Add("#Return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// Read your data
}
conn.Close();
int resultCount = (int)cmd.Parameters["#Return"].Value;
return resultCount;
When you added the Parameter, did you set the Direction to ReturnValue?
Yep I did - I'm using the sqlDataSource control which sniffed out the params for me including the return value with the correct direction set. Just for fun I did also create the param from scratch with return val direction too but no joy :(
Run this in the SQL tools to ensure that the stored proc behaves as expected.
DECLARE #rtn int;
EXEC #rtn = dbo.delete_treatment_category /*insert valid id here > 2*/;
SELECT #rtn;
I mention "an id > 2" because you may be reading the wrong parameter.
That is, this stored proc has 2 parameters... one for the id and the other for the return value.
IIRC:
cmd.CommandType = CommandType.StoredProcedure 'cmd is SqlCommand
Dim retValParam as New SqlParameter("#RETURN_VALUE", SqlDbType.Int)
retValParam.Direction = ParameterDirection.ReturnValue
cmd.Parameters.Add(retValParam)
'add the ID parameter here
'execute
'look at the #RETURN_VALUE parameter here
You don't show the code where you are adding the parameters and executing the command. Both may be critical.
I know one way of reproducing this - if your procedure also returns rows (for example, from a DELETE trigger), and you haven't consumed those rows... basically, the out/return parameter values follow the grids in the TDS stream, so if you haven't read the grids yet (when using ExecuteReader) - then you can't get the updated parameters / return value. But if you are using ExecuteNonQuery this shouldn't be a factor.
Why do you use Name="RETURN_VALUE" for the Delete parameter but Name="RetVal" for Update and Insert? If the latter two work, that is the first place I'd look.

ASP.net: Sqldatasource and Session variable

<asp:HiddenField ID="hfDualInitials" runat="server" Visible="false" OnInit="hfDualInitials_OnInit" />
<asp:SqlDataSource ID="sdsStoreNo" runat="server" ConnectionString="<%$ ConnectionStrings:ConnStr %>"
SelectCommand="select * from AccountCancellation_Process
where store_num in (select distinct storeno from franchisedata where initials in (#DualInitials))
order by CustomerName ASC" >
<SelectParameters>
<asp:ControlParameter ControlID="hfDualInitials" DbType="String" Name="DualInitials" />
</SelectParameters>
</asp:SqlDataSource>
I have a Sqldatasource with the above select command and the below code to set the hiddenfield value
Protected Sub hfDualInitials_OnInit(ByVal sender As Object, ByVal e As EventArgs)
Dim _DualInitials As String = "('P2','7T')"
Session.Add("DualInitials", _DualInitials)
Me.hfDualInitials.Value = Session("DualInitials")
End Sub
I'm mocking the Session with ('P2','7T') that is going to pass into the above sql command.
when i run the query:
select * from AccountCancellation_Process where store_num in (select distinct storeno from franchisedata where initials in ('P2','7T'))
it return some data but in my Sqldatasource select command. It return nothing. my guess is because of the where initials in (#DualInitials) the ( ) that is already in the hiddenfield but if i remove the ( ) and just have #DualInitials. I will get "Incorrect syntax near '#DualInitials'."
Does anyone know any workaround or where i get it wrong?
Check out answers to the ADO.NET TableAdapter parameters question.
You have a query with a string parameter, not an array parameter. So, when you pass "('P2','7T')" you think that the final query is
WHERE initials IN ('P2', '7T')
In reality it is
WHERE initials IN ('(''P2'', ''7T'')')
If it is only going to be two initials then just rewrite using the OR statement. Otherwise I don't know good solution outside of those mentioned in the other thread.
You can't paramterize an IN statement in SQL like that. You'll have to use string concatenation of the SQL instead (bad) or some other technique like parsing a delimited string.
Without running the sample, I can't be sure, but what about
WHERE initials IN (<%=Eval(#DualInitials)%>)

Resources