Pass parameter id to sql query using url routing - asp.net

I'm a beginner asp.net developer
Trying to create my first simple news portal pages.
Here is what I have:
Database
Admin_News.aspx to add news into database
Default.aspx to display all news with the title linkable
NewsDetails.aspx to display the details by ID when they click on the title in Default.aspx
How I did That:
in Default.aspx I used this code:
<div>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<HeaderTemplate>
<table border="1">
<tr>
<td>
<b>title</b>
</td>
<td>
<b>news</b>
</td>
<td>
<b>imges</b>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:HyperLink runat="server" ID="hl" NavigateUrl='<%#"~/NewsDetails.aspx?id=" + Eval("id")%>' Text='<%# Eval("title") %>'></asp:HyperLink>
</td>
<td>
<%# DataBinder.Eval(Container.DataItem, "news")%>
</td>
<td>
<img alt="" src='<%# DataBinder.Eval(Container.DataItem, "imageurl")%>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MoneyHolderConnectionString %>"
SelectCommand="SELECT [id], [title], [news], [imageurl], [detail] FROM [News]"></asp:SqlDataSource>
</div>
NewsDetails.aspx code:
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:MoneyHolderConnectionString %>"
SelectCommand="SELECT [title], [news], [imageurl], [detail] FROM [News] WHERE ([id] = #id)">
<SelectParameters>
<asp:QueryStringParameter Name="id" QueryStringField="id" Type="Int64" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource2">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<h1 align="right"><br />
<strong><p style="color:#000">
<%# DataBinder.Eval(Container.DataItem, "title")%>
</strong></h1><p/><br />
<br />
<p align="center"><img src='<%# DataBinder.Eval(Container.DataItem, "imageurl")%>'/>
<p/>
<br />
<br />
<p id="detail" align="right" style="font-size:25px"><%# DataBinder.Eval(Container.DataItem, "detail")%><p/>
<br />
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
so what I'm doing is displaying the article according to the ID in .aspx?id= in the url.
everything was working fine.. until I used the url routing.
I changed/added some codes to change the structure of the url I don't want it to appear like ~/NewsDetails.aspx?id=1
I want to be like ~/News/1 instead with the same result.
So I have added this code to Global.asax:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routeCollection)
{
routeCollection.MapPageRoute("RouteForNews", "News/{id}", "~/NewsDetails.aspx");
}
and I added this code to the NewsDetails.aspx.cs code behind:
string id = Page.RouteData.Values["id"].ToString();
and I changed the NavigateUrl in NewsDetails.aspx to:
NavigateUrl='<%#"~/News/" + Eval("id")%>'
now when I open Default.aspx the news appear with the titles linkable to ~/News/"id number", when i click on a title, NewsDetails.aspx opens with the link of /News/idnumber but no data inside..its empty i only can see the design of the master page.
I would appreciate any help from you what should I do to display the news, the id value in the url it goes to string id variable but I don't know how to pass it to the sql query (i'm not sure if this is the problem)

You should not use the asp:QueryStringParameter in the asp:SqlDataSource in the NewsDetails page, as your parameter is no longer in the QueryString. A QueryString is the part of URL that comes after the question mark.
Use this link to know how to pass parameters to select statement:
How to pass variable to SelectCommand of SqlDataSource?

connectionstring="<%$ ConnectionStrings:MyConnection %>"
selectcommand="SELECT Name, Age FROM ContactInfo where
State=#StateCode">

Related

Cannot access Ajax Rating from code behind

I have this html markup:
<div id="profil_rating_container">
<div id="profil_rating">
<div id="pr">
<h2 id="rating" class="profil_rating_title">Hodnocení <asp:Label ID="lblAddRating" runat="server"><span><i class="fa fa-plus-circle"></i></span></asp:Label></h2>
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajaxToolkit:ToolkitScriptManager>
<ajaxToolkit:Rating ID="FinalRating" runat="server" MaxRating="5" ReadOnly="true" StarCssClass="ratingStar" WaitingStarCssClass="savedRatingStar" FilledStarCssClass="mainFilledRatingStar" EmptyStarCssClass="mainEmptyRatingStar" />
<br />
<asp:SqlDataSource ID="RatinSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:SportovniPlanetaCS %>"
SelectCommand="SELECT [RatingText], [RatingCount], [Name] FROM [rating] WHERE ([ProfileId] = #ProfileId) AND ([RatingText] IS NOT NULL)">
<SelectParameters>
<asp:QueryStringParameter Name="ProfileId" QueryStringField="id" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Repeater ID="RatingRepeater" DataSourceID="RatinSqlDataSource" runat="server" OnItemDataBound="RatingRepeater_ItemDataBound">
<ItemTemplate>
<h4><asp:Literal ID="RatingName" runat="server" Text='<%# Eval("Name") %>' /></h4>
<p class="p_rating"><asp:Literal ID="RatingText" runat="server" Text='<%# Eval("RatingText") %>'></asp:Literal></p>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblRating" runat="server" Text="Uživatel zatím nemá žádné hodnocení." Visible="false"></asp:Label>
</FooterTemplate>
</asp:Repeater>
</div>
</div>
</div>
And when I am accesing Ajax Control Toolkit Rating from code behind like this: FinalRating.CurrentRating = cmdRating.ExecuteScalar it underline FinalRating with error text: 'Final Rating' is not declared. It may be inaccessible due to its protection level.
I don't know why this is happening. I have the same code in other 5 pages and it is working finec, but in this one page it isn't. Also when I add new page and add Ajax Rating, I cannot access it from code behind. The rating control isn't in any data component like repeater or datalist. Can this be solved by FindControl? If yes, how exactly?
Does anyone know, what is causing this problem? Thanks for answer.

My query works in Access, but not in Visual Studio [duplicate]

This question already has an answer here:
Query returns no records to show on my webpage
(1 answer)
Closed 9 years ago.
I have a query that I have run in Access that doesn't seem to run when I execute it on my website site. Here's the code for the webpage that I want the database to populate content for:
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/TravelJoansDB.accdb"
SelectCommand="SELECT * FROM [Table2] INNER JOIN BlogEntryItems ON Table2.ID=BlogEntryItems.BlogID AND Table2.ID=#ID">
<SelectParameters>
<asp:QueryStringParameter Name="ID" QueryStringField="Table2.ID" Type="Decimal" />
</SelectParameters>
</asp:AccessDataSource>
<asp:DataList ID="DataList1" DataSourceID="AccessDataSource1"
runat="server" ItemStyle-CssClass="picTableStyle"
DataKeyField="Table.2ID">
<ItemStyle></ItemStyle>
<ItemTemplate>
<table>
<tr>
<td>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "PlaceImages/" + Eval("Image") %>' /><br />
<asp:Label ID="Label1" CssClass="picCaptionStyle" runat="server" Text='<%# Eval("Caption") %>' />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label4" class="picBodyText" runat="server" Text='<%# Eval("PicStory") %>' />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
When I take out the join, it works fine. I add the join and it doesn't give me any error or anything, it just seems as though there are no results for it to show on my website. Any ideas?
Note that I haven't worked on AccessDataSource. However, looking at the docs - here is what you should look into
Change the query to use ? instead of #ID
SelectCommand="SELECT * FROM [Table2] INNER JOIN BlogEntryItems ON Table2.ID=BlogEntryItems.BlogID AND Table2.ID= ?"
Because the AccessDataSource control extends the SqlDataSource class
and uses the System.Data.OleDb provider, you specify parameter
placeholders using the "?" placeholder character.
ref: http://msdn.microsoft.com/en-us/library/8e5545e1%28v=vs.100%29.aspx
If the above doesn't work, omit the data type (Decimal) of the parameter OR specify a relevant type such as Integer instead.

Delete row from a programmatically created table

In an asp.net listview I'm putting a table
<ItemTemplate>
<tr>
<td style="width:90%"><asp:TextBox Enabled="false" ID="txtOverall" Text='<%#Eval("Overall") %>' runat="server"></asp:TextBox></td>
<td style="width:10%"><asp:Button ID="cmdDelete" OnClick="DeleteRow" ToolTip='<%#Eval("tooltip") %>' class="alert tiny button" Text="x" runat="server" /></td>
</tr>
</ItemTemplate>
Which basically is a text string and next to it I want a button that will delete the row that the button appears on. The table holds more fields than this but for simplicity this the basic structure. All of the data is entered programmatically. Does anyone know how I can remove a single row from the table?
Thanks,
Craig
You need to handle the delete command
private void OnRecordDeleting(Object source, SqlDataSourceCommandEventArgs e) {
//your deleting code
}
and asp
<asp:SqlDataSource
id="SqlDataSource1"
runat="server"
DataSourceMode="DataSet"
ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
SelectCommand="SELECT * FROM Orders"
OnDeleting="OnRecordDeleting"
OnDeleted="OnRecordDeleted">
</asp:SqlDataSource>

Creating posts and comments similar to Facebook

I need my own posts and comment on the page in my project, something similar to Facebook. I succesfully created posts by using sql table, sqldatasource and repeater. But I have a problem with comments.
I created sql table Comments, there is a column with Post ID. This is my code:
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:MotWebConnectionString %>"
SelectCommand="SELECT * FROM [Posts]
JOIN [Users] ON [Users].[UserName] = [Posts].[UserName]
JOIN [Comments] ON [Comments].[PostId] = [Posts].[PostId]
WHERE ([GroupId] = #GroupId) ">
<SelectParameters>
<asp:QueryStringParameter Name="GroupId" QueryStringField="id" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource3" >
<ItemTemplate>
<table style="width: 100%;">
<tr>
<td width="10%">
<asp:Image ID="Image2" runat="server" Width="64px" Height="64px" ImageUrl='<%# Eval("ProfilePicture")%>' />
</td>
<td align="left" width="90%" >
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("UserName", "~/_/Profile.aspx?Username={0}")%>'><p><asp:Literal ID="Literal2" runat="server" Text='<%# Eval("Username")%>'></asp:Literal></p></asp:HyperLink>
</td>
</tr>
</table>
<asp:Literal ID="Literal3" runat="server" Text='<%# Eval("Text")%>'></asp:Literal>
<br />
<asp:Literal ID="Literal4" runat="server" Text='<%# Eval("CommentText")%>'></asp:Literal>
<asp:FormView ID="FormView2" runat="server" DataSourceID="SqlDataSource4" DefaultMode="Insert" >
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" CommandName="Insert" />
</InsertItemTemplate>
</asp:FormView>
</ItemTemplate>
<SeparatorTemplate>
<br />
<br />
<br />
</SeparatorTemplate>
</asp:Repeater>
But it shows only posts, where is at least 1 comment and if there are more comments than 1, the posts is twice or more times on the page.
And another problem is, that I don't know how to insert right Post ID into the Comments table. It is probably by using Parameter...
My database schema (I did't know how to create it in SQL Management Studio, so it is in VS):
http://img685.imageshack.us/img685/1416/vstiekd.jpg
Please could anyone help me with this:
How to view right comments under the post and view also posts without any comment
How to insert the comment with right Post ID
I will be very thankfull for any kind of help

ASP.NET VB Nested Listviews

I have an outer listview and inside its itemtemplate an inner listview. Each has its own SQLDataSource. A Id field from the outerlistview works as a select parameter for the second listview.
When stepping through with the debugger it works perfectly, unfortunately the rendered page only contains data from the outer listview. It appears the databinding of the outer listview fires and renders the page (including the inner listview) before the codebehind can provide a where parameter to the second listview.
The aspx page is below.
<%# Page Title="Nested ListView" Language="VB" MasterPageFile="~/MasterPages/SimpleMasterPage.master"
CodeFile="NLV2PA_A.aspx.vb" Inherits="Demos_NLV2PA_A" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:ListView ID="ListView1" runat="server" ItemPlaceholderID="PlaceHolder1" DataKeyNames="Id"
DataSourceID="SqlDataSource1">
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
</LayoutTemplate>
<EmptyDataTemplate>
<span>ListView 1 No data was returned. </span>
</EmptyDataTemplate>
<ItemTemplate>
<span style="">Id:
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>' />
<br />
Name:
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
<br />
<br />
</span>
<asp:ListView ID="ListView2" runat="server" ItemPlaceholderID="PlaceHolder2" DataSourceID="SqlDataSource2">
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="PlaceHolder2"></asp:PlaceHolder>
</LayoutTemplate>
<EmptyDataTemplate>
<span>ListView2 No data was returned. </span>
</EmptyDataTemplate>
<ItemTemplate>
<span style="">Title:
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
<br />
<h1>
<%# Eval("Title") %></h1>
<br />
Summary:
<asp:Label ID="SummaryLabel" runat="server" Text='<%# Eval("Summary") %>' />
<br />
PhotoAlbumID:
<asp:Label ID="PhotoAlbumIdLabel" runat="server" Text='<%# Eval("PhotoAlbumId") %>' />
<br />
<br />
</span>
</ItemTemplate>
</asp:ListView>
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RenaissanceConnectionString1 %>"
SelectCommand="SELECT [Id], [Name] FROM [PhotoAlbum] ORDER BY [Id]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:RenaissanceConnectionString1 %>"
SelectCommand="SELECT [Title], [Summary], [PhotoAlbumId] FROM [Apartments] WHERE ([PhotoAlbumId] = #PAId)">
<SelectParameters>
<asp:ControlParameter ControlID="ListView1" DefaultValue="0" Name="PAId" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>
The code behind is
Protected Sub ListView1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles ListView1.ItemDataBound
If e.Item.ItemType = ListViewItemType.DataItem Then
SqlDataSource2.SelectParameters("PAId").DefaultValue = DirectCast(e.Item.FindControl("IdLabel"), Label).Text
End If
End Sub
The output to the browser is:
Id: 8
Name: First set of Photos
ListView2 No data was returned.
Id: 9
Name: Second set of Photos
ListView2 No data was returned.
etc.
Microsoft make the point in an old article that:
You could, in theory, intercept the
ItemDataBound event of the parent
ListView, walk your way through the
control tree, grab a reference to the
child ListView, and bind it
programmatically to data. If you do,
you won't throw an exception, but the
binding command on the inner ListView
is lost because it fires too late to
affect the rendering.
Unfortunately, they don't tell me how to fix it.
If there is any genius out there who could tell me how to get this to work it would be much appreciated.
Put your SqlDataSource2 inside the ItemTemplate of ListView1.
for your ControlParameter, set ControlID="IdLabel" and PropertyName="Text"
You wont need any code behind

Resources