ASP.net: Sqldatasource and Session variable - asp.net

<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)%>)

Related

How do you filter an ASP.NET Entity Framework Bound ListView via DropDownList?

I am having some trouble figuring out the best way to filter an Entity Framework Query with the results of a DropDownList's Selected Value to fill a ListView Control.
My code is as follows:
Public Function ListViewProducts_GetData() As IQueryable
Dim strVendorName As String = ddlFilterVendor.SelectedValue
Dim myEntities As New InventoryProductsEntities()
Return (From product In myEntities.InventoryProducts
Order By product.ID Ascending
Where product.VendorID = strVendorName
Select product).Take(ddlDisplayRecords.SelectedValue)
End Function
This is pretty rough right now, but I would like to be able to filter this data by vendor, and then page it, but I cannot get the ListView to display the updated queried data. It just continues to display the same data as before, even with a ddlFilterVendor.SelectedValue change.
The drop down list code is as follows:
<asp:DropDownList ID="ddlFilterVendor" runat="server" AutoPostBack="True" DataSourceID="SqlDataSourceVendor" DataTextField="VendorID" DataValueField="VendorID" AppendDataBoundItems="True">
<asp:ListItem Selected="True">All</asp:ListItem>
</asp:DropDownList>
I am stuck at this point.... I was thinking about posting the ddlFilterVendor.SelectedValue to the QueryString and reloading the page, but I would imagine that there should be an easier way to do this. Any help or ideas would be greatly appreciated! Thanks!
The SqlDataSource Code is as follows:
<asp:SqlDataSource ID="SqlDataSourceVendor" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" SelectCommand="SELECT DISTINCT [VendorID] FROM [InventoryProducts]"></asp:SqlDataSource>
I have found a solution to this problem. In the DropDownList's SelectedIndexChanged event, I called the following method:
ListViewProducts.DataBind()
This re-queried the database with the appropriate Vendor filter, as shown in code snippet:
Public Function ListViewProducts_GetData() As IQueryable
Dim strVendorName As String = ddlFilterVendor.SelectedValue
Dim myEntities As New InventoryProductsEntities()
Return (From product In myEntities.InventoryProducts
Order By product.ID Ascending
Where product.VendorID = strVendorName
Select product).Take(ddlDisplayRecords.SelectedValue)
End Function
Thanks!

<asp:QueryStringParameter> doesn't seem to be passing a value to my SQL stored procedure

I'm passing a partial name to an aspx page in the url in order to filter a list of names. However, the parameter seems to be completely ignored. The url is FilterPage.aspx?strPartialName=abi
The .Net code is:
<ul id="employees">
<asp:Repeater ID="rptEmployees" DataSourceID="sqlGetEmployees" runat="server">
<ItemTemplate>
<li><%# Eval("Name")%></li>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource
id="sqlGetEmployees"
ConnectionString = "dsn=EmpDB;"
ProviderName = "System.Data.Odbc"
SelectCommand = "cdlSP_GetEmployees"
SelectCommandType = "StoredProcedure"
CancelSelectOnNullParameter="false"
runat="server">
<asp:SelectParameters>
<asp:QueryStringParameter Name="strPartialName" DbType="String" Direction="Input"
QueryStringField="strPartialName" DefaultValue="" ConvertEmptyStringToNull="True" />
</asp:SelectParameters>
</asp:SqlDataSource>
</ul>
And the SQL stored procedure is:
ALTER PROCEDURE [dbo].[cdlSP_GetEmployees] #strPartialName varchar(100) = Null
AS
BEGIN
SET NOCOUNT ON
DECLARE #sql VARCHAR(1600)
--Get all records is strPartialName is null
IF #strPartialName IS NULL
BEGIN
SELECT LN + ' ' + FN AS Name
FROM dbo.Employees
ORDER BY Name
END
ELSE
BEGIN
SELECT LN + ' ' + FN AS Name
FROM dbo.Employees
WHERE LN LIKE '%' + #strPartialName + '%' OR FN LIKE '%' + #strPartialName + '%'
ORDER BY Name
END
END
I added in a Response.Write ("strPartialName=" & Request.QueryString("strPartialName") to the page and it shows as "abi" as expected. I also modified the stored procedure to see if the "Null" condition was firing instead of the ELSE condition (I modified the code to only return the last name). Sure enough, the data being returned was just the employee last names, meaning the strPartialName was being passed as null instead of as "adi". I can't for the life of me figure out why? Anyone?
on the parameter your missing the size. size="100". and the type is SqlDbType.VarChar (this is codebehind form.not sure how to put this in tag form. i assume it is just DbType="varchar") not string

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.

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..

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

Resources