ASP.NET Repeater question - asp.net

I have a repeater control and under the ItemTemplate, I have Image control. Anyway the old
How can I set the ImageUrl programatically?
Anyway, the old html code I have was like this:
<ItemTemplate>
<img src="<%# Eval("ImageSource") %>" alt="" />
</ItemTemplate>
But I want to check if the image exists in directory or not then I can setup with temp image.
I have a code but .. it's not really working so there's no sense of showing it here. Can you guys help me? Should I use ItemCreated or ItemDataBound event?

In the xml side in the template, you need to call a method directly.
<asp:Image runat="server" ID="myImg" ImageUrl='<%# MyImageUrlFunction(Eval("DataFieldName").ToString()); %>' />
You need a corresponding method in the code behind defined publicly:
public string MyImageUrlFunction(string field)
{
// put some logic here to determine url
return imageUrl;
}

In your ItemDataBound, do something like:
protected void rpt_ItemDataBound(object sender, RepeaterEventArgs e)
{
HtmlImage img = (HtmlImage)e.Item.FindControl("img");
string imageUrl = (string)DataBinder.Eval(e.Item.DataItem, "ImageSource");
if (File.Exists(imageUrl))
img.Src = imageUrl;
}
That's System.Web.UI.HtmlControls.HtmlImage, System.Web.UI.DataBinder and System.IO.File.

ItemDataBound. You can get the control reference through the current item's findcontrol event, and then check to see that the image exists. You can get the file path using Server.MapPath("~/images/test.png"), and then if it doesn't, inject your own.
You can also use a public method that the client-side markup can call, pass in the URL, and provide a default if it doesn't exist.
HTH.

<ItemTemplate>
<asp:Image ImageUrl='<%# System.IO.File.Exists(Eval("ImageSourceProperty").ToString()) ? Eval("ImageSourceProperty").ToString() : TemporaryImagePath %>' runat="server" />
</ItemTemplate>

for the Error
The server tag is not well formed
You should remove extra space in your code!
<%# System.IO.File......%>
should be <%#System.IO.File......%>

Related

How to bind image gallery with sql data table in asp.net?

I have binary data in SQL database of images.And there may be multiple records of any single ID.Means there may be multiple images for one ID.
And i have to fetch binary data of images from database and convert into image and bind with image gallery.
I am working on ASP.NET 4.0.
I want to do that without any third party control.
Can any one help me out on this ?
you need to write your binary value on response using
HttpContext.Current.Response.BinaryWrite()
first you need to set the ImageUrl attribute of an image element to a empty aspx page, or an ashx handler, as a better choice.
and then send the id of record which has the binary value as querystring to that page, like this:
<asp:Image ID="Image1"
runat="server"
CssClass="w120px h120px"
ImageUrl='ImageHandler.ashx?imageID=1' />
and then in code behind of that specific page (ashx handler, in our case) you need to get binary value from your dbase and write to response like this:
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string id = HttpContext.Current.Request.QueryString["imageID"];
var image = GetBinaryImageFromDataBaseByRecordID(id);
context.Response.ContentType = "image/jpeg"; // you need to set this to content-type of your image
context.Response.BinaryWrite(image);
}
private byte[] GetBinaryImageFromDataBaseByRecordID(string ImageRecordID)
{
throw new Exception(); // you need to get binary value from db using ImageRecordID and return;
}
public bool IsReusable
{
get
{
return false;
}
}
}
if you have more than one image for a subject, for example 3 images, you can use 3 image element, and they request to existed handler like this:
<asp:Image ID="Image1"
runat="server"
CssClass="w120px h120px"
ImageUrl='ImageHandler.ashx?imageID=1' />
<asp:Image ID="Image2"
runat="server"
CssClass="w120px h120px"
ImageUrl='ImageHandler.ashx?imageID=20' />
<asp:Image ID="Image3"
runat="server"
CssClass="w120px h120px"
ImageUrl='ImageHandler.ashx?imageID=30' />
you need to have a page, which id of your subject is passed to, then in that page you need to create a DataList or repeater or some other data controls and get a query from db and bind image records of that subject to your control, and create image element in DataList or some other data control, for each record, and set the ImageUrl of image element when your data control DataList, for example is bound, something like this:
<asp:DataList ID="DataList2" runat="server"
RepeatColumns="4"
RepeatDirection="Horizontal">
<ItemTemplate>
<asp:Image ID="Image1"
runat="server"
CssClass="w120px h120px"
ImageUrl="ImageHandler.ashx?imageID=<%# Eval("ID") %>" />
</ItemTemplate>

Bind control's ID property to object property

I have the following repeater control, which is bound to collection of DashboardPage objects. DashboardPage has the following properties: Name, Pagenumber .
<asp:Repeater ID="reportPages" runat="server">
<ItemTemplate>
<asp:ImageButton runat="server" onclick="ImageButton_Click"
ImageUrl="<%# GetImagePath(Container.DataItem) %>"
onmouseover="<%# GetMouseOverEventString(Container.DataItem) %>"
onmouseout="<%# GetMouseOutEventString(Container.DataItem) %>"
/>
</ItemTemplate>
<SeparatorTemplate>
</SeparatorTemplate>
</asp:Repeater>
I want to bind ImageButton's ID property to Name property of DashboardPage object, something like this
ID="<%# Eval('Name') %>"
But an exception is thrown:
The ID property of a control can only be set using the ID attribute in the tag and a simple value.
I need the ID property of the image, because I have a client side script which changes the image, using the it's ID. Is there a way around this?
Thanks for replies
Regards
Gagik Kyurkchyan
Since you have found you cannot dynamically set the ID of a server control you need to find an alternative way of referencing your image using JavaScript. There are three ways I can think of:
Set the CssClass property of the control and use that instead. It's a little more inefficient to find a control by class rather than ID using DOM, but that is probably negligible in the real world.
Wrap your image in a standard DIV. and set the ID on the container DIV. You can then use something like jQuery to go $("#divid img")...
Use a standard <img> tag (with no runat="server") rather than an asp:Image control. You can then set the ID on that without issue.
You can use ItemDataBound to set the ID.
CODEBEHIND:
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var textbox = e.Item.FindControl("myTextBox");
textbox.ID = "myTextBox" + (e.name).toString(); /*ToString() method can be unnecessary in some cases.*/
}
REPEATER:
<asp:Repeater ID="myRepeater" runat="server" OnItemDataBound="BehaviorCustomizeRepeater_ItemDataBound">
/*other stuffs*/
</asp:Repeater>

Add text after expression <%$ ... %>

In my ASPX page I've this:
<h3>
<asp:HyperLink runat="server"
NavigateUrl="<%$ Resources:Path, Article%>"
Text='<%# Eval("title") %>' />
</h3>
For the NavigateUrl attribute I want to specify an ID like
NavigateUrl="<%$ Resources:Path, Article%>?id=4"
But when I do that the expression is not precessed by the ASP parser.
How can I do that?
Don't do this in markup. You have a server control here -- give it an ID (say, ID="NavigationLink", and then do something like this in your .cs file:
void Page_Load(object sender, EventArgs e)
{
// I'm guessing that "4" was just an example here, so fill that piece in with a function you can call to create the proper ID.
NavigationLink.NavigateUrl = Properties.Resources.Path + Properties.Resources.Article + "?id=4"
}
Edit: I'm assuming that when you say <%$ Resources:Path, Article%> that you're trying to reference the Path and Article entries in your resources file, but upon further reflection, it's hard to tell exactly what you're doing. Can you be more specific here?
You can define a protected function in the code behind class and call it from the markup. Like this:
<h3>
<asp:HyperLink runat="server"
NavigateUrl="<%# GetNavigateUrl(Eval("ID")) %>" <%-- Passing an ID as a parameter for example --%>
Text='<%# Eval("title") %>' />
</h3>
Code behind:
// Again, idObj is just an example. Any info from the data item can be passed here
protected string GetNavigateUrl(object idObj)
{
int id = (int)idObj;
string urlFromResources = // retrieving the url from resources
return urlFromResources + '?ID=' + id;
}
You could retrieve the resource values programmatically, in your code-behind, and set the NavigateUrl property from there.
Try String.Format...
<% =String.Format({0}?id={1}, Request.ApplicationPath, 4) %>
It looks like you're mixing some other language into this (javascript?).
Also, don't forget to give your server-side controls an ID.

Set Custom ASP.NET UserControl variables when its in a Repeater

<%# Register Src="~/Controls/PressFileDownload.ascx" TagName="pfd" TagPrefix="uc1" %>
<asp:Repeater id="Repeater1" runat="Server" OnItemDataBound="RPTLayer_OnItemDataBound">
<ItemTemplate>
<asp:Label ID="LBLHeader" Runat="server" Visible="false"></asp:Label>
<asp:Image ID="IMGThumb" Runat="server" Visible="false"></asp:Image>
<asp:Label ID="LBLBody" Runat="server" class="layerBody"></asp:Label>
<uc1:pfd ID="pfd1" runat="server" ShowContainerName="false" ParentContentTypeId="55" />
<asp:Literal ID="litLayerLinks" runat="server"></asp:Literal>
</ItemTemplate>
</asp:Repeater>
System.Web.UI.WebControls.Label lbl;
System.Web.UI.WebControls.Literal lit;
System.Web.UI.WebControls.Image img;
System.Web.UI.WebControls.HyperLink hl;
System.Web.UI.UserControl uc;
I need to set the ParentItemID variable for the uc1:pdf listed inside the repeater.
I thought I should be able to find uc by looking in the e.Item and then setting it somehow. I think this is the part where I'm missing something.
uc = (UserControl)e.Item.FindControl("pfd1");
if (uc != null) { uc.Attributes["ParentItemID"] = i.ItemID.ToString(); }
Any thoughts would be appreciated.
Also tried this with similar results... when I debug inside my usercontrol (pfd1) the parameters I am trying to set have not been set.
uc = (UserControl)e.Item.FindControl("pfd1");
if (uc != null)
{
uc.Attributes.Add("ContainerID", _cid.ToString());
uc.Attributes.Add("ParentItemId", i.ItemID.ToString());
}
UPDATE: It looks like my controls are not connected by a namespace. I've wrapped by the parent control (Layer) and the PressFileDownlad control in a namespace "MyControls". Also updated their Inherits reference on the aspx to read "MyControls.xxxxx". I'm able to type "MyControls.Layer" inside the code on layer.aspx.cs but I'm not able to get "MyControls.PressFileDownload"
If you implement ParentItemID as a public property in your user control, then you should be able to set it declaratively, e.g:
<asp:Repeater id="Repeater1" ...>
<ItemTemplate>
<uc1:pfd ID="pfd1" runat="server" ParentItemId='<%# Eval("ItemID") %>' ... />
Martin is right you should be able to set it in declarative way (in case your property is public) .
But your way should also work (just cast it properly)
((PressFileDownload)e.Item.FindControl("pfd1")).ParentItemId = 0;
The best way is to implement the OnDataBinding event for the user control. I try to stay away from putting code inline in the aspx using webforms if possible.
When the repeater gets bound, for each item that is bound, the OnDataBinding will fire for your user control and your handler can do what it needs. You don't have to go searching for the controls.
Here is an example:
// in your aspx
<uc1:pfd ID="pfd1" runat="server" ShowContainerName="false" ParentContentTypeId="55"
OnDataBinding="pfd1_DataBinding" />
// in your codebehind implement the OnDataBinding event
protected void pfd1_DataBinding(object sender, System.EventArgs e)
{
pfd uc = (pfd)(sender);
uc.ContainerID = _containerID.ToString();
uc.ParentItemID = Eval("ItemID");
// Here you can do more like access other items like hidden fields
// or cached objects or even other controls etc... Skys the limit.
}
EDIT: Notice from your comment you require more data than what is found in the datasource. In this case what I usually do is just make private member variables in the .cs that I store data in. So when you have the container ID just store it in a variable that will be accessible.
Eg in your .cs for your page:
public partial class _TestPage : System.Web.UI.Page
{
private int _containerID { get; set; }
Then when you load the data just set the _containerID property and it will be accessible in the OnDataBinding event. Just make sure you are binding after you have set the _containerID.

asp.net hyperlnk control

Is it possible to call a class's static property to set the navigateurl property?
<asp:HyperLink ID="hlRegister" NavigateUrl="<%= SomeClass.Property %>" runat="server" />
without using codebehind ofcourse!
You don't need code behind. You can just try it, like i just did. I created a simple page with exactly the code you have, and then created a class called SomeClass with a property named Property. It worked fine for me the way that you have it set up above.
Edit: Ok, it didn't compile with an error.. but It's giving me not the result I'm looking for.
http://localhost:3061/Sample/%3C%=%20SomeClass.Property.ToString()%20%%3E
using:
public static class SomeClass
{
public static string Property
{
get { return "http://www.google.com"; }
}
}
and
<asp:HyperLink ID="hlRegister" NavigateUrl='<%= SomeClass.Property.ToString() %>' Text="Goooooogle" runat="server" />
You can do this, but to avoid a syntax error you must modify your example to be as follows.
<asp:HyperLink ID="hlRegister"
NavigateUrl='<%= SomeClass.Property %>' runat="server" />
Notice the small difference of using single quotes rather than double around the script.
However, one might really ask why not just do it in the codebehind.
sure, in the code behind:
hl.NavigateUrl = Class.Static().ToString();

Resources