how to pass a GUID to a select query of SqlDataSource - asp.net

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" />

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.

ASP.NET / VB.NET : Generate Insert Command

I have all of my form variables in my codebehind, they were all retrieved using "Request.Form".
As Far as I Know..If I use the SQLDataSource to do this I have to use ASP.NET Controlls(which I do not want).
INSERT INTO Orders(FirstName, LastName, Email, PhoneNumber, Address, City, State, ZipCode, PaymentMethod, PromoCode, OrderStatus, Tracking, PPEmail, SubmissionDate) VALUES (#FirstName, #LastName, #Email, #Phone, #Address, #City, #State, 11111, #PaymentMethod', '0', 'New Order - Pending', '0', #PPEMAIL, #Date)
CodeBehind
Dim fPrice As String = CType(Session.Item("Qprice"), String)
Dim DeviceMake As String = CType(Session.Item("Make"), String)
Dim PaymentMethod As String = Request.Form("Payment Type")
Dim DeviceModel As String = CType(Session.Item("Model"), String)
Dim DeviceCondition As String = CType(Session.Item("Condition"), String)
Dim SubmissionDate As String = Date.Now.ToString
Dim FirstName = Request.Form("First")
Dim LastName = Request.Form("Last")
Dim City = Request.Form("City")
Dim Phone = Request.Form("Phone")
Dim Address = Request.Form("Address")
Dim State = Request.Form("State")
Dim Zip = Request.Form("Zip")
Dim Email = Request.Form("EMail")
Is there a way I can attatch my variables to the insert statment generated by the SQLDatasource, without having to manually code the parameters?
You could use FormParameter. This doesn't require any ASP.NET control so far I'm aware.
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:MyNorthwind %>"
selectcommand="SELECT CompanyName,ShipperID FROM Shippers"
insertcommand="INSERT INTO Shippers (CompanyName,Phone) VALUES (#CoName,#Phone)">
<insertparameters>
<asp:formparameter name="CoName" formfield="CompanyNameBox" />
<asp:formparameter name="Phone" formfield="PhoneBox" />
</insertparameters>
</asp:sqldatasource>
Pay special attention to Microsoft warning in relation to this mechanism
The FormParameter does not validate the value passed by the form element in any way; it uses the raw value. In most cases you can validate the value of the FormParameter before it is used by a data source control by handling an event, such as the Selecting, Updating, Inserting, or Deleting event exposed by the data source control you are using. If the value of the parameter does not pass your validation tests, you can cancel the data operation by setting the Cancel property of the associated CancelEventArgs class to true.
Its probably better that you forcibly attach the parameters. As you are getting your values from Form and Session (ick), parameterizing the SQL will give you some measure of protection.
You may want to explore code generation (A-la T4), this way you can point the codegen at a proc/table and it will generate the vb code to call it, attach the params and execute the statement.

Get scope_identity returned value

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

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