asp.net HyperLink dynamic creation of NavigateUrl path - asp.net

I have this in my asp.net page:
<% foreach (Product item in ProductList())
{
%>
<div id="i<%:item.CODE %>" class="item" dir="rtl">
<label class="code"><%:item.CODE %></label>
<asp:HyperLink runat="server" ID="DetailsLink" Text="Details"
NavigateUrl="~/Details.aspx?ProductCode=<%:item.CODE %>" font-size="18px"></asp:HyperLink>
</div>
<% } %>
Although the first <%:item.CODE%> works and I can see the item's code written,
in the NavigateUrl string it does not work.
I get a link to "http://localhost:34546/Details.aspx?ProductCode=<%:item.CODE %>"
How can I concat the item's code to the link?

Try this
<% foreach (String str in new string[] { "Apple", "Mango", "Orange" })
{
%>
<div id="i<%: str %>" class="item" dir="rtl">
<label class="code">
<%: str %></label>
<a href='<%: "Details.aspx?ProductCode=" + str %>'>DetailsLink</a>
</div>
<% } %>
instead of
<asp:HyperLink runat="server"
ID="DetailsLink"
Text="Details"
NavigateUrl="~/Details.aspx?ProductCode=<%:item.CODE %>"
font-size="18px"/>

You should use repeater control & handle its ItemDataBound event.
That will make you code cleaner & easy to debug.
in your .aspx.cs file:
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Product item = e.Item.DataItem as Product ;
HyperLink DetailsLink = e.Item.FindControl("DetailsLink") as HyperLink;
DetailsLink.NavigateUrl= "~/Details.aspx?ProductCode=" + item.CODE;
}
}
protected void Page_Load(object sender, EventArgs e)
{
rpt.DataSource = ProductList();
rpt.DataBind();
}
in your .aspx file:
<asp:Repeater ID="rpt" runat="server"> <ItemTemplate>
<asp:HyperLink runat="server" ID="DetailsLink" Text="Details"
font-size="18px"></asp:HyperLink>
</ItemTemplate>
</asp:Repeater>

Related

Difficulty in displaying data using repeater

I am trying to display shopping categories with its sub categories and sub-sub categories using repeater.. Data is binding but it is not being displayed.. Can anyone help why?
here's my code:
.aspx file
<asp:Repeater ID="CategoryRepeater" runat="server" OnItemDataBound="CategoryRepeater_OnItemDataBound">
<ItemTemplate>
<a href='Clothing.aspx?CategoryId=<%#Eval("CategoryId") %>'<%#Eval("CategoryName") %>></a><br />
<asp:Repeater ID="SubCategoryRepeater" runat="server" OnItemDataBound="SubCategoryRepeater_OnItemDataBound">
<ItemTemplate>
<a href='Clothing.aspx?CategoryId=<%#Eval("CategoryId") %>&SubCategoryId=<%#Eval("SubCategoryId") %>'<%#Eval("SubCategoryName") %>></a><br />
<asp:Repeater ID="SubSubCategoryRepeater" runat="server">
<ItemTemplate>
<a href='Clothing.aspx?CategoryId=<%#Eval("CategoryId") %>&SubCategoryId=<%#Eval("SubCategoryId") %>&SubSubCategoryId=<%#Eval("SubSubCategoryId") %>'<%#Eval("SubSubCategoryName") %>></a><br />
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
C# Code:
protected void CategoryRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem))
{
DataRowView dataItem = e.Item.DataItem as DataRowView;
int categoryId = Convert.ToInt32(dataItem["CategoryId"]);
Repeater rp = (Repeater)e.Item.FindControl("SubCategoryRepeater");
ds = us.SelectSubCategories(categoryId);
rp.DataSource = ds;
rp.DataBind();
}
}
protected void SubCategoryRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem))
{
DataRowView dataItem = e.Item.DataItem as DataRowView;
int SubCategoryId = Convert.ToInt32(dataItem["SubCategoryId"]);
Repeater rp1 = (Repeater)e.Item.FindControl("SubSubCategoryRepeater");
ds1 = us.SelectSubSubCategories(SubCategoryId);
rp1.DataSource = ds1;
rp1.DataBind();
}
}
Check your source code to make sure nothing is being output to the page. I think you just have the category name being rendered inside the anchor tag.
Here is the same code with the evals simplified to see what is going on
<a href='Clothing.aspx?CategoryId={catid}'{name}></a>
Should be:
<a href='Clothing.aspx?CategoryId={catid}'>{name}</a>
or
<a href='Clothing.aspx?CategoryId=<%#Eval("CategoryId") %>'><%#Eval("CategoryName") %></a>
Same mistake was done in all three locations.
I think everything is correct from the code, but your output is wrong.
You are doing this:
<a href='Clothing.aspx?CategoryId=<%#Eval("CategoryId") %>&SubCategoryId=<%#Eval("SubCategoryId") %>'<%#Eval("SubCategoryName") %>></a><br />
But it needs to be
<a href='Clothing.aspx?CategoryId=<%#Eval("CategoryId") %>&SubCategoryId=<%#Eval("SubCategoryId") %>'><%#Eval("SubCategoryName") %></a><br />
Noticed I moved the '>' back behind <%# Eval("SubCategoryName")%>

Cannot access checkbox checkedchanged event inside DataList

I have checkboxes inside a datalist itemtemplate..But i cant access checkbox chechedchange event. I set AutoPostBack as true. But still cant fire event.
Here my codes.
<ul class="commentlist" >
<asp:DataList ID="datalistYorum" runat="server" DataSourceID="ods_yorumlar"
RepeatLayout="Flow" ItemStyle-Wrap="True" RepeatDirection="Horizontal"
onitemcreated="datalistYorum_ItemCreated"
onitemdatabound="datalistYorum_ItemDataBound" onload="datalistYorum_Load"
ondatabinding="datalistYorum_DataBinding">
<ItemTemplate>
<li class="comment">
<div class="comment-body">
<div class="comment-author vcard">
<div class="lightbox-photo">
<a class="image-overlay" href='<%# "Foto/profil/foto_buyuk/" + Eval("Yorum_Profil_Foto_Buyuk") %>' data-rel="prettyPhoto" title='<%# Eval("Yorum_UserName")%>'>
<img src='<%# "Foto/profil/foto_kucuk/" + Eval("Yorum_Profil_Foto_Kucuk") %>' alt='<%# Eval("Yorum_UserName")%>' class="avatar" />
</a>
</div>
<cite class="fn"><asp:HyperLink ID="linkProfil" runat="server" Text='<%# Eval("Yorum_UserName")%>' NavigateUrl='<%# "~/profil.aspx?user_id="+ Eval("User_ID") %>'></asp:HyperLink></cite>
<cite class="fn-time"><%# Eval("Yorum_Gecen_Zaman")%></cite>
</div>
<p><%# Eval("Yorum_Text")%></p>
<div class="reply"><asp:CheckBox ID="checkLike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" />
<asp:ToggleButtonExtender ID="ToggleButtonLike" runat="server" TargetControlID ="checkLike" ImageHeight="32" ImageWidth="52" CheckedImageUrl="~/images/liked.png" UncheckedImageUrl="~/images/like.png" CheckedImageAlternateText="Like">
</asp:ToggleButtonExtender>
</div>
<div class="reply"><asp:CheckBox ID="checkDislike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" />
<asp:ToggleButtonExtender ID="ToggleButtonDislike" runat="server" TargetControlID="checkDislike" ImageHeight="32" ImageWidth="62" UncheckedImageUrl="~/images/dislike.png" CheckedImageUrl="~/images/disliked.png">
</asp:ToggleButtonExtender>
</div>
</div>
</li>
</ItemTemplate>
</asp:DataList>
<asp:ObjectDataSource ID="ods_yorumlar" runat="server"
DataObjectTypeName="Yorum" TypeName="yonet" SelectMethod="PostYorumlariGetir"
ondatabinding="ods_yorumlar_DataBinding"
onselecting="ods_yorumlar_Selecting" onselected="ods_yorumlar_Selected">
<SelectParameters>
and code behind:
protected void datalistYorum_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
CheckBox checkLike = (CheckBox)e.Item.FindControl("checkLike");
CheckBox checkDislike = (CheckBox)e.Item.FindControl("checkDislike");
if (!Page.IsPostBack)
{
checkLike.CheckedChanged += new EventHandler(checkLike_CheckedChanged);
checkDislike.CheckedChanged += new EventHandler(checkDislike_CheckedChanged);
}
}
}
public void checkLike_CheckedChanged(object sender, EventArgs e)
{
object user_id = Membership.GetUser().ProviderUserKey;
DateTime event_date = DateTime.Now;
CheckBox checkLike = (CheckBox)datalistYorum.FindControl("checkLike");
if (checkLike.Checked == true)
{
try
{
using (SqlConnection baglanti = new SqlConnection(ConfigurationManager.ConnectionStrings["xxx"].ConnectionString.ToString()))
{
SqlCommand komut = new SqlCommand("sp_likeordislike", baglanti);
komut.CommandType = CommandType.StoredProcedure;
komut.Parameters.AddWithValue("#comment",1);
komut.Parameters.AddWithValue("#user_id", user_id);
komut.Parameters.AddWithValue("#likeordislike", 1);
komut.Parameters.AddWithValue("#event_date", event_date);
baglanti.Open();
komut.ExecuteNonQuery();
baglanti.Close();
}
}
catch (Exception)
{
throw;
}
}
}
But nothing happen.Thanks!
Unless you are adding the event handler for the 'checklike' Checkbox in Page_Load it looks as though the assignment is missing.
Change the 'checklike' Checkbox declaration as follows:
<asp:CheckBox ID="checkLike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" OnCheckedChanged="checkLike_CheckedChanged" />
Try this:
protected void checkDislike_CheckedChanged(Object sender, EventArgs e)
{
CheckBox cb = (CheckBox) sender;
DataListItem item = (DataListItem) cb.NamingContainer;
//
//
}
Your markup will look like this:
<asp:CheckBox ID="checkDislike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" OnCheckedChanged="checkDislike_CheckedChanged" />
Before trying this comment out all the other checkbox events
Check this link:

Repeater inside repeater not binding properly

I have a repeater inside another. Like so :
<asp:Repeater ID="CategoryRepeater" runat="server" OnItemDataBound="ItemBound">
<ItemTemplate>
<div class="groupbox">
<fieldset>
<legend><%# Container.DataItem %></legend>
<table>
<asp:Repeater ID="ItemRepeater" runat="server">
<ItemTemplate>
<tr>
<td>
<asp:CheckBox id="chkItem" runat="server" Text='<%# Eval("Text")%>' />
<asp:Button ID="btnXRefs" Text="x-refs" runat="server" CssClass="xRefButton" OnClick="btnSelectXRefs_Click" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</fieldset>
</div>
</ItemTemplate>
</asp:Repeater>
CODE BEHIND :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (var db = new DbContext())
{
CategoryRepeater.DataSource = db.Categories.OrderBy(x => x.Heading).Select(x => x.Heading).Distinct();
CategoryRepeater.DataBind();
}
}
}
protected void ItemBound(object sender, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.Item)
{
Repeater childRepeater = (Repeater)args.Item.FindControl("ItemRepeater");
var item = args.Item as RepeaterItem;
using (var db = new DbContext())
{
childRepeater.DataSource = db.Categories.Where(x => x.Heading == item.DataItem).OrderBy(x => x.Text);
childRepeater.DataBind();
}
}
}
My goal is to first make many groupboxes using the top level, then bind items into each one. So I end up with many small stacked lists of checkboxes.
Problem is, all the top level boxes appear, yet only the first one contains checkbox items, ie. only the first one is bound internally, and the ItemBound method is only called once for the first one.
Any ideas why?
This line
if (args.Item.ItemType == ListItemType.Item)
Should be like this
if(args.Item.ItemType = ListItemType.Item ||
args.Item.ItemType == ListItemType.AlternatingItem)

Conditionally show image in a repeater if the database is not null

I have a repeater that includes as image. However, there is an image that may not be in all of the Promotions in this repeater
<div class="promo">
<h2><%# ((Promotion)Container.DataItem).Title %></h2>
<p><img src="/Uploads/<%# ((Promotion)Container.DataItem).Image %>" alt="" class="promoImg" /><%# ((Promotion)Container.DataItem).Description %></p>
<p><em><%# ((Promotion)Container.DataItem).Restrictions %></em></p>
</div>
Can someone show me how to make the only show up if that entry does not have a null field?
I prefer do something in server side, so, my sugestion is:
Add a event handler to your repeater
<asp:Repeater ID="myRpt" runat="server" onitemdatabound="myRpt_ItemDataBound" >
<ItemTemplate>
<div class="promo">
<h2>
<%# ((Promotion)Container.DataItem).Title %></h2>
<p>
<asp:Image ID="imgTest" CssClass="promoImg" ImageUrl="" runat="server" />
<%# ((Promotion)Container.DataItem).Description %></p>
<p>
<em>
<%# ((Promotion)Container.DataItem).Restrictions %>
</em>
</p>
</div>
</ItemTemplate>
</asp:Repeater>
i will "bind" the image source in code behind, you could do it for other controls too.
So, the code behind is:
protected void myRpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Image imgTest = (Image)e.Item.FindControl("imgTest");
Promotion pActual = (Promotion)e.Item.DataItem;
bool needToShowImage = !String.IsNullOrEmpty(pActual.Image)
if (needToShowImage)
{
imgTest.ImageUrl = "Uploads/" + pActual.Image;
}
else
{
imgTest.Visible = false;
}
}
}
It will do the trick. If it dont work, please, let me know.
This should do the trick:
For C#.Net:
<div class="promo">
<h2><%# ((Promotion)Container.DataItem).Title %></h2>
<p><img runat="server" visible='<%# Information.IsDBNull(((Promotion)Container.DataItem).Image) %>' src=""/Uploads/<%# ((Promotion)Container.DataItem).Image.ToString %>" alt="no image found" class="promoImg" /><%# ((Promotion)Container.DataItem).Description %></p>
<p><em><%# ((Promotion)Container.DataItem).Restrictions %></em></p>
</div>
I've added some jquery to check each image on the page to make sure there is a image associated with that promotion:
$(document).ready(function () {
$('.promoImg').each(function (index) {
if ($(this).attr('src') == "/Uploads/") {
$(this).hide();
}
});
});
I'm still interested in a server side solution
I think you can use panel to do this.
<div class="promo">
<h2><%# ((Promotion)Container.DataItem).Title %></h2>
<asp:Panel ID="pnlImage" runat="server">
<p><img src="/Uploads/<%# ((Promotion)Container.DataItem).Image %>" alt="" class="promoImg" /><%# ((Promotion)Container.DataItem).Description %></p>
</asp:Panel>
<p><em><%# ((Promotion)Container.DataItem).Restrictions %></em></p>
In ItemDataBound event, do this
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
if (((Promotion)e.Item.DataItem).Image == null) {
((Panel)e.Item.FindControl("pnlImage")).Visible = false;
}
when panel is invisible, it will not be rendered.
why not use the
<% if()%>
to judge either there is a image source? if not ,then didn't response.so we can save more

select index of listView is not working in ASP.NET

I am new to ASP.NET, I am making a search box in my application.
For example: if a user enters "abc" in the textbox, then the textbox will fetch data from the database which starts with "abc". I am passing this data to DataTable.
It works properly,
Here is my code snippet:
DataTable result = new DataTable();
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string query = string.Format("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '{0}%'", TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
result.Load(cmd.ExecuteReader());
conn.Close();
lvwItems.DataSource = result;
lvwItems.DataBind();
}
Now I want to retrieve all this data in my <div> tag. so i tried using asp:ListView,
here is my code snippet,
it works properly, but now i want to navigate to new page when user select any row of listView, but i am unable to select any row..
<asp:ListView ID="lvwItems" runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
</div>
</ItemTemplate>
Thanks In Advance !!
Any help will be appreciated.
EDIT:(SearchBox.aspx.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class SearchBox : System.Web.UI.Page
{
string connString;
DataTable result = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{ }
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string query = string.Format("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '{0}%'", TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
result.Load(cmd.ExecuteReader());
conn.Close();
lvwItems.DataSource = result;
lvwItems.DataBind();
}
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("lablId");
if (String.IsNullOrEmpty(lablId.Text))
{
Response.Redirect("NextPage.aspx?id=" + lablId.Text, false);
}
}
(SearchBox.aspx)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SearchBox.aspx.cs" Inherits="SearchBox" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:TextBox ID="TextBox1" runat="server" Height="30px" Width="179px"
OnTextChanged="TextBox1_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Go"
Width="62px" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
<asp:Label ID="lablId" visible="false" runat="server" Text='<%#Eval("Scrip") %>'/>
</div>
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:krunal_DBConnectionString2 %>"
SelectCommand="SELECT * FROM [SearchBoxData]"></asp:SqlDataSource>
</form>
</body>
</html>
You have to add a SELECT button in the ItemTemplate, see the complete working code.
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<%# Eval("Scrip")%>
<asp:LinkButton ID="SelectButton" runat="server" CommandName="Select" Text="Select" />
</ItemTemplate>
</asp:ListView>
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("CONTROL_ID");
}
Thanks
Deepu
Probably you will have to add the event for Selected index change:
<asp:ListView ID="lvwItems" runat="server" ItemPlaceholderID="plhItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging">
In code behind you can get the selected row item like below.
Also you can place a label or hidden field so that you can get some data from those control and pass it in to the next page.. (might be id or something).
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
<asp:Label ID="lablId" visible="flase" runat="server" Text='<%#Eval("Id") %>' />
</div>
</ItemTemplate>
</asp:ListView>
void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("lablId");
if (String.IsNullOrEmpty(lablId.Text))
{
Response.Redirect("page.aspx?id="+lablId.Text,false);
}
}
Thanks
Deepu
Here you go,
Also remove the OnClick="callMethod" from the button. Since you have SelectedIndex method no need to have the onClick method.
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Button btn = (Button)item.FindControl("btn1");
if(btn != null)
{
var buttonText = btn.Text;
}
}
Hope this helps
Thanks
Deepu

Resources