How to bind image gallery with sql data table in asp.net? - 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>

Related

the reapter to display the first 100 characters of a string and after that a hyperlink to display next page

use a reapeter to display data, but sometimes the data is to big to be displayed in a cell. Can I use a method to allow the reapter to display the first 100 characters of a string and after that a hyperlink to display next page? any help is welcome!
You don't have the implementation details of your code, so this is a shot in the dark. If you are binding an object, create a new property that takes the first 100 characters of the information you want displayed:
class Foo
{
public String PropertyData {get;set;} //your real data;
public String DisplayData //bind the reader to this property instead.
{
get
{
return PropertyData.substring
(0, (PropertyData.Length >= 100) ? 100 : PropertyData.Length);
}
}
}
You can have the property return anything you want, this is just an example of how to get it to display only 100 characters.
You can leave this logic in the view:
<asp:Label runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "your_text_field").ToString().Substring(0, Math.Min(100, DataBinder.Eval(Container.DataItem, "your_text_field").ToString().Length %>' />
<asp:Hyperlink runat="server" Test='<%# Eval("your_text_field") %>'
Visible='<%# Eval("your_text_field").ToString().Length > 100 %>' />

ASP.NET Repeater question

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

Using hyperlink control with imagefield control in gridview

I have a gridview and a column of that gridview is displaying images whose path is stored in a database & image is stored in locale folder inside my website. My problem is that I want to use the hyperlink control with the image, so that when the image is clicked it should jump to another page. How can I do that?
Firstly, you should bind data to your grid (in the code-behind):
public override void DataBind()
{
// you implementation of getting data
yourGridId.DataSource = GetData();
yourGridId.DataBind();
}
Then I'd suggest to use template field for your image:
<asp:gridview id="yourGridId"
runat="server">
<columns>
<asp:templatefield headertext="An Image">
<itemtemplate>
<a href="pageWhereToGo.aspx">
<img src='<%# ResolveUrl((string)Eval("ImageUrl"))%>' />
</a>
</itemtemplate>
</asp:templatefield>
</columns>
</asp:gridview>
The code above is assuming that the paths to images in your database are stored as a relative paths from your application (e.g. ~/assets/images/image1.jpg) or as full paths (e.g. http://www.contoso.com/assets/images/image1.jpg). Also assuming that your data source holds a path to image in ImageUrl field.
So the example above is a simplest grid with one asp:templatefield column: here is a clickable image which goes to the pageWhereToGo.aspx page on click event.
More about Gridview Column Fields could be found here.
Instead of using DataBound fields you can also use TemplateFiled within a GridView:
<asp:TemplateField HeaderText="SomeText" >
<ItemTemplate>
// Put any kind of .NET Code in here
// you can access the data bound values like this:
<%# Eval("NameOfPropertyOnDataBoundObject")%>
</ItemTemplate>
<ItemStyle CssClass="tworows"></ItemStyle>
</asp:TemplateField>

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.

How can I display an image in a repeater or grid control?

I have around 200 images to be displayed on a page.
The database only stores the path where image is located. Images themselves are stored in the application's folder. EG: d:/application/website/images/
I need to convert the original size image to a thumbnail image while displaying the thumbnail
Is there any functionality to do this?
Ideally, the display would have 5 rows and 5 columns, and then use paging to display the rest of the data.
Essentially, an image gallery: The app shows a thumbnail image on the grid/repeater page, and when the user clicks on that thumbnail a new pop up window opens displaying the entire image. Can I make this work with the repeater control?
Any idea how to display the thumbnail images in repeater control.
Are there any web sites which can help me out?
First off, I need to say that storing the thumbnails on the server would probably be much more efficient than this solution. Some of the principles in this code would be usable for creating these thumbnails as the images are uploaded. That would probably be a better way to go.
That being said, here is a possible solution. This was hacked together really quickly, but it does work. I use something similar to serve up attachments from a database. Create a new ashx page as follows:
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Bitmap b = new Bitmap(#"c:\temp\pictures\" + context.Request.QueryString["filename"]);
Image i = b.GetThumbnailImage(48, 48, null, System.IntPtr.Zero);
using (MemoryStream ms = new MemoryStream())
{
i.Save(ms, ImageFormat.Jpeg);
context.Response.BinaryWrite(ms.ToArray());
}
context.Response.ContentType = "image/jpeg";
}
public bool IsReusable
{
get
{
return false;
}
}
}
This will find a file who's name is passed in from the query string and create the thumbnail and use a memory stream to display the image. You will obviously have to adjust for path, error handling, ensuring mime types are correct, etc.
Once you have this complete, you can use this URL (something like http://localhost/Handler.ashx?filename=myFirstImage) in a repeater to generate your thumbnails.
I know this post is very old now but still it might be helpfull for anyone. I had same issue and used this coding.
Config File
<add key="WebResources" value="~/Assets/WebResources/" />
<add key="ImageRoot" value="Images\Web" />
<add key="ProfileImages" value="Images\Profile" />
Asp.Net Datalist
<asp:DataList ID="dlPrivateAlbum" runat="server" OnItemCommand="dlPublicAlbum_ItemCommand" RepeatDirection="Horizontal" RepeatLayout="Flow">
<ItemTemplate>
<div class="boxgrid captionfull">
<asp:Literal ID="lit_ImagePath" runat="server" Text='<%# Eval("URL") %>' Visible="false" />
<asp:HyperLink runat="server" Target="_blank" ToolTip='<%#Eval("Description") %>'
ImageUrl='<%# ConfigurationManager.AppSettings["WebResources"] + ConfigurationManager.AppSettings["ProfileImages"] + #"\thumbs\" + Eval("URL") %>'
NavigateUrl='<%# ConfigurationManager.AppSettings["WebResources"] + ConfigurationManager.AppSettings["ProfileImages"] + #"\" + Eval("URL") %>' />
<div class="cover boxcaption">
<asp:LinkButton ID="lnkbtn_Edit" runat="server" CommandArgument='<%# Eval("ID") %>' CommandName="edit" CssClass="captionlink" Text='<%#Eval("Title") %>' />
</div>
</div>
</ItemTemplate>
CSS :
.boxcaption{float:left;position:absolute;background:#000;height:70px;width:100%;opacity:.8;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=80);-MS-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=80)"}
.captionfull .boxcaption{top:230px;left:0}
.caption .boxcaption{top:190px;left:0}
.captionlink:link, .captionlink:visited {color: #E2E2E2;text-decoration: none;}
.captionlink:hover { text-decoration: underline; }
.captionlink:active {color: #F5F5F5;}
Code behind :
private void load(Guid userID)
{
try
{
loadOptions();
DbContext = new Entities();
user = DbContext.UserProfiles.FirstOrDefault(d => d.UserID == userID);
List<Album> albums = DbContext.Albums.Where(d => d.UserID == userID).ToList();
if (albums != null)
{
dlPublicAlbum.DataSource = albums.FirstOrDefault(d => d.Type == "public").Images;
dlPublicAlbum.DataBind();
}
}
catch (Exception ex)
{
Msg.ShowAlert(this.Parent.Page, Msg.GeneralError_Title + " " + ex.GetType().Name, ex.Message, MsgType.Error);
}
}

Resources