efficient asp.net sql query - asp.net

Been using this site for years and have always found it very helpful and normally all my questions get answered by reading the site.
I have some case studies on a site than need to be related to other sections of the site and i am using this code to pull the records from the database :-
<div id="sidebar">
<asp:accessdatasource
id="cskey"
runat="server"
datasourcemode="DataSet"
datafile="_db/db.mdb"
selectcommand="SELECT id FROM markets_case_assign WHERE productid = #catid">
<SelectParameters>
<asp:QueryStringParameter Name="catid" QueryStringField="id" DefaultValue="1" />
</SelectParameters>
</asp:accessdatasource>
<asp:Repeater id="cskeycontent" runat="server" DataSourceID="cskey">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Visible="false" Text='<%#Eval("id")%>'></asp:Label>
<asp:accessdatasource
id="csval"
runat="server"
datasourcemode="DataSet"
datafile="_db/db.mdb"
selectcommand="SELECT id,title,company FROM casestudies WHERE id = #pid">
<SelectParameters>
<asp:controlparameter name="pid" controlid="Label1" DefaultValue="1" />
</SelectParameters>
</asp:accessdatasource>
<asp:Repeater id="csvalcontent" runat="server" DataSourceID="csval">
<ItemTemplate>
<div class="case-studies">
<h2><%#Eval("company")%></h2>
<p><%#Eval("title")%></p>
<p class="no-margin-bottom">Read case study</p>
</div>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</div>
I was just wondering if there is a simpler way of doing it.
Any help would be much appreciated.
Cheers Andy

i was wondering if there was a way of doing it with only one query
To make it one query, just change the SQL call as:
SELECT id,title,company FROM casestudies
WHERE id IN (SELECT id FROM markets_case_assign WHERE productid = #catid)
and use only one repeater (the inner one).
Now you lose the extra advanced to separate them with some extra header, line etc..

Related

if statement in asp.net ASP.DataList vb.net

In Classic ASP I was able to display a section break based on state. I have an SQL table with menu items, columns:(ListOrder(int),BeginUrl(varchar(20),ShowDate(varchar(20),EndUrl(varchar(20),Section(varchar(20)) BeginURL,ShowDate,EndUrl concatenate to create the link. Section is state (WA,OR,ID).
In classic I created a var nLevel set to "" then proceed to loop through the RS.
Do While NOT menuRS.EOF
If menuRS.Fields("Section") <> nLevel Then
Response.Write("<br><br>" & menuRS.Fields("Section"))
nLevel = menuRS.Fields("Section")
End If
If menuRS.Fields("Display") = 0 Then
Response.Write("<br>"& menuRS.Fields("BeginUrl")&menuRS.Fields("ShowDate")&menuRS.Fields("EndUrl")) & VbCrLf
End If
menuRS.MoveNext
Loop
Which would give me (roughly)
WA
[date]
[date]
OR
[date]
[date]
ID
[date]
Trying to duplicate that in .Net using a DataList, ItemTemplate, and ASP:Label of course using VB, is giving me fits on the 'section' break.
I have the main menu items looping out. Just failing on the Section Break.
<asp:DataList ID="MenuList1" runat="server" DataSourceID="NwccMenuList">
<ItemTemplate>
<asp:Label ID="SectionBreak" runat="server"
Text='<%# If(Eval("Section") <> Me.nLevel) Then (Eval("Section") Me.nLevel= Eval("Section") End If%>' />
</ItemTemplate>
<ItemTemplate>
<asp:Label ID="BeginUrlLabel" runat="server"
Text='<%# Eval("MenuUrl") %>' />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="NwccMenuList" runat="server"
ConnectionString="<%$ ConnectionStrings:nwcctanningConnectionString %>"
SelectCommand="SELECT ([BeginUrl]+[ShowDate]+[EndUrl]) AS MenuUrl, Section
FROM [Menu] WHERE ([Display] = 0) ORDER BY [Section] DESC, [ListOrder]">
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="Display"
Type="Byte" />
</SelectParameters>
</asp:SqlDataSource>
Not sure the nLevel variable (in codefile) is reachable or not cannot get past the If statement!
I appreciate any pointers or where I went wrong!
Generally, you want to replace one dinosaur code with another ancient code. OK, Let's do it in ASP.NET way. First, asp:DataList is not the best choice because it renders table. Use the simplest databound control like asp:Repeater. This is a sample code which do the work declarativelly.
<asp:Repeater ID="rptMenu" runat="server" DataSource="NwccMenuList">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<FooterTemplate></ul></FooterTemplate>
<ItemTemplate>
<li>
<asp:Literal runat="server" ID="ltrSection" Text='<%#Eval("Section") %>'></asp:Literal>
<asp:Repeater runat="server" DataSource="sqlSubmenu">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<FooterTemplate></ul></FooterTemplate>
<ItemTemplate>
<li>
<asp:HyperLink runat="server" Text='<%#Eval("MenuUrl") %>' NavigateUrl='<%#Eval("MenuUrl") %>'></asp:HyperLink>
</li>
</ItemTemplate>
</asp:Repeater>
<%-- Note that a child datasource is inside parent ItemTemplate --%>
<asp:SqlDataSource ID="sqlSubmenu" runat="server"
ConnectionString="<%$ ConnectionStrings:nwcctanningConnectionString %>"
SelectCommand="SELECT ([BeginUrl]+[ShowDate]+[EndUrl]) AS MenuUrl
FROM [Menu] WHERE ([Display] = 0 and Section=#section) ORDER BY [ListOrder]">
<SelectParameters>
<%-- literal control from parent ItemTemplate --%>
<asp:ControlParameter ControlID="ltrSection" Name="section" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</li>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="NwccMenuList" runat="server"
ConnectionString="<%$ ConnectionStrings:nwcctanningConnectionString %>"
SelectCommand="SELECT distinct Section FROM [Menu] WHERE ([Display] = 0) ORDER BY [Section] DESC">
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="Display"
Type="Byte" />
</SelectParameters>
</asp:SqlDataSource>
Again, this approach is more than 10 year old.

Creating a Separate Detail View Page in ASP.net

OK, so I've created a form that has 2 connecting drop down list. I have a button that redirects to another page. This one is currently blank, but I've tried adding a detail view to it, however, when I try and connect it to the data source it just shows the first of the column names and abc.
I need to know how to connect it to my data source which would create 4 rows and the corresponding information for those rows. In this case it would be something akin to Quantity, Category, Product Name, and the Description for the item selected on the first page.
Any help is seriously appreciated.
UPDATE
I still can't get this working.
Here is a screenshot of page one.
My instructions for this page are simply...
On the first screen, a user chooses a category and then chooses a product from the selected category. The Category and Product controls are populated using the following procedures: So I set up both of these with the respective procedures, and they work fine.
The order detail button simply redirects to the order detail page, but I'm not sure if I have to do anything to save the selection.
However, here is the code I've put together for those 3 buttons.
<div style="height: 182px">
Category: <asp:DropDownList ID="ddlCategory"
runat="server" DataSourceID="SqlDataSource1" DataTextField="CategoryName"
DataValueField="CategoryId" AutoPostBack="True"/>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$
ConnectionStrings:DeveloperInterviewConnectionString %>"
SelectCommand="CategoryListing" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
<br/>
Product: <asp:DropDownList ID="ddlProduct"
runat="server" DataSourceID="SqlDataSource2" DataTextField="ProductName"
DataValueField="ProductId"/>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$
ConnectionStrings:DeveloperInterviewConnectionString %>"
SelectCommand="CategoryProducts" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCategory" Name="CategoryId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<input type="button" value="Order Details"
onClick="location.href = 'OrderDetails.aspx';">
So do I have to do anything to setup the data to go from one form to the next, and I still can't get the view operational.
Ok, So I tried linking up your stored proc to a details view and didn't get very far with it. I think the problem is the output params.
Try modifying the stored proc to the following:
CREATE PROCEDURE [dbo].[ProductDetails]
#ProductId INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT
ProductName,
ProductDescription,
QuantityInStock
from Product
where productid = #ProductId
END
GO
Point the datasource at that Sproc, link up the ProductID param and you should be set.
UPDATE: adding my asp.net code
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataSourceID="SqlDataSource1">
<Fields>
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="ProductDescription" HeaderText="ProductDescription" SortExpression="ProductDescription" />
<asp:BoundField DataField="QuantityInStock" HeaderText="QuantityInStock" SortExpression="QuantityInStock" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DemoDBConnectionString %>" SelectCommand="ProductDetails" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="1" Name="ProductId" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>

How to access a value which is associated with a dropdownlist item?

This is my dropdown list code........
<td valign="top" align="center">
<asp:DropDownList ID="StudentNameDropDownList" runat="server" Width="150px"
DataSourceID="SqlDataSource2" DataTextField="StudentName"
DataValueField="StudentName" AutoPostBack="True">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:dbbilling2.0ConnectionString3 %>"
SelectCommand="SELECT [StudentID], [StudentName] FROM [tblStudentInfo] WHERE ([Class] = #Class)">
<SelectParameters>
<asp:ControlParameter ControlID="ClassDropDownList" Name="Class"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<br />
Now I want to access the Student ID field in my code behind file..How can i achieve this?? What syntax i must use[like dropdownlist.selecteditem] ??
First of all in your DropDownList asp component you must set the property DataValueField="StudentID", then in your code behind you can get the Id of the selected student by writing : StudentNameDropDownList.SelectedValue
For Id You can try this code
StudentNameDropDownList.SelectedValue

Dropdown List appears empty when using #parameter

I am trying to make a dropdownlist work for me. A user can be in many 'Field1's, so I wanted the dropdown to show those Field1s.
Currently what happens is I just get a blank list. Here is a sample of the code:
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT DISTINCT Field1 FROM table
WHERE (Field3= #Field3)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="Field3" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
If I remove the select parameters and the WHERE clause the list of all DHBs appears - it just seems to have issues with #Field3.
Edit: I have tested the query in SQL Server and it works for me (by replacing #Field3 with a known value)
Any suggestions? I am very new to asp.net, and have next to nothing in the .cs file (besides some authorisation and such), so if people could point me in the right direction that would be fantastic.
Edit 2: It would probably help if I gave you the whole template:
<asp:TemplateField HeaderText="Field1" SortExpression="Field2">
<EditItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Field2") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource2" DataTextField="Field1" DataValueField="Field1">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="Field1 FROM table
WHERE (Field3 = #Field3)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="Field3" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
You're populating another control using Dropdownlist selectedValue as a parameter, that is dictated by your code. In this case
You're missing property in the controlParameter
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Property="SelectedValue" Name="Field3" Type="String" />
</SelectParameters>
If you're trying to populate DropDownList1 you're completely derailed. In this case you need to show up more markup code and details.
Update: You cannot take the parameters value from the DropDownList control which you're populating. Either remove the parameter or use another control to provide the value

FormView.FindControl works for one form but not the other on the same page

I have two Formviews on the same page. I can use FindControl on the first without issue, but it always fails on the second one.
I am using the ItemTemplate for both, both default to ReadOnly, both are bound to SQLDataSources (different ones) but I cannot for the life of me work out why FindControl works for one and not the other.
I have removed a lot of the plain text from the code below.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SoftSaleDBConnectionString %>"
SelectCommand="SELECT * FROM [Apps] WHERE ([AppID] = #AppID)" >
<SelectParameters>
<asp:FormParameter FormField="AppID" Name="AppID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:FormView ID="FormView1" runat="server" DataKeyNames="AppID"
DataSourceID="SqlDataSource1">
<ItemTemplate>
<h1>
<asp:Label ID="AppNameLabel" runat="server" Text='<%# Bind("AppName") %>' />
<asp:Label ID="VersionLabel" runat="server" Text='<%# Bind("Version") %>' /> for
<asp:Label ID="OSLabel" runat="server" Text='<%# Bind("OS") %>' />
</h1>
<p>Text here</p>
<p><asp:TextBox ID="LicenseTextBox" runat="server"
Text='<%# Eval("License")%>'
TextMode="MultiLine" Width="800px" Rows="25" ReadOnly="True"></asp:TextBox></p>
<asp:HiddenField ID="AppLocation" runat="server" ViewStateMode="Inherit" Value='<%# Bind("AppLocation") %>'/>
</ItemTemplate>
</asp:FormView>
<p><asp:Literal ID="SizeLiteral" runat="server"></asp:Literal></p>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:SoftSaleDBConnectionString %>"
SelectCommand="SELECT * FROM [Installations] WHERE (([AppID] = #AppID) AND ([Username] = #Username))" >
<SelectParameters>
<asp:FormParameter FormField="AppID" Name="AppID" Type="Int32" />
<asp:FormParameter FormField="Username" Name="Username" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:FormView ID="DLFormView" runat="server" DataSourceID="SqlDataSource4"
DataKeyNames="AppID,Username">
<ItemTemplate>
<p> <asp:Label ID="DLAppNameLabel" runat="server" />
<br />
<br />
<asp:Label ID="NumberOfInstallations" runat="server" Text='<%# Bind("Installations") %>'></asp:Label>
<br />
<asp:HiddenField ID="TotalInstallations" runat="server" />
Number of New Installations:
<asp:DropDownList ID="NumberOfNewInstallations" runat="server">
</asp:DropDownList>
<br />
<asp:Label ID="TotalNumberOfInstallations" runat="server" Text="Label"></asp:Label>
</p>
</ItemTemplate>
</asp:FormView>
And the FindControl coding is as follows...
TextBox LicTextBox = (TextBox)FormView1.FindControl("LicenseTextBox");
HiddenField AppLocCode = (HiddenField)FormView1.FindControl("AppLocation");
Label AppNameCode = (Label)FormView1.FindControl("AppNameLabel");
These always work...
Label DLAppNameCode = (Label)DLFormView.FindControl("DLAppNameLabel");
This always returns null. I've read a million bosts about the controls not being rendered until databinding has completed, but surely if the two FOrmViews are set up the same way, the result should be the same.
Any help would be much apreciated :)
Matt :)
I'd like to plead stupidity and but also provide some background to how I've used what I've learnt from my stupidity.
My SqlDataSource for DLFormView was returning records, of course I then used slightly different values by accident and so no records were returned. I only figured this out by making the ItemTemplate section of the form view only contain unbound (basically plain text) data. As nothing displayed, this pointed towards the page using a different tempalte. When I put a test line in the EmptyDataTemplate, it displayed, confirming there was nothing returned by the SqlDataSource. Perhaps a School boy error not putting something in this template during development.
As it happens I need to use the EmptyDataTemplate anyway, I just hadn't got to this point. As only one template is rendered at a time, I have been able to use the same ID names in both templates. This means there is no need to test for which template is being used. (although empty template is used when DataItemsCount = 0, otherwise you can test for CurrentMode for the remaining templates.)
So a big fail on my part, but I hope people can learn from my mistake.
Matt :)

Resources