asp.net Gridview ImageField alternate Image - asp.net

I have below gridview with an imagefield linked with the UserID number.
How can I do if the picture dosnt exist in the specifield older to get an standard alternate picture?
<ItemTemplate>
<asp:Image ID="MainPic" runat="server"
ImageUrl='<%# GetImageUrl(Eval("PerfilId") as string)%>' />
</ItemTemplate>
..
protected string GetImageUrl(string dbImgURL)
{
if (File.Exists(dbImgURL))
{
return dbImgURL;
}
else
{
return "AdminFotoUser/UserPics/BGP1.png";
}
}

Well you can check the image path in onRowDataBound event of the GridView and change it to a common image if file doesn't exist.
using System.IO;
if (File.Exists(path))
{
Console.WriteLine("file exists");
}
else
//Find Control and Bind it to a common image
OR
You could have re-worked your grid a different way:
- instead of using an Image Field column, you could have used a template column like this:
Code:
<asp:TemplateField>
<ItemTemplate>
<asp:Image runat="server" ID="myImg"
ImageUrl='<%# GetImageUrl(Eval(col2) as string) %>' />
</ItemTemplate>
</asp:TemplateField>
Then in your code behind, you have create a function to return the correct image url:
Code:
Updated Ans
//Send Image name from database (DataGrid) as dbImgURL
protected string GetImageUrl(string dbImgURL)
{
if (File.Exists(dbImgURL))
{
return dbImgURL;
}
else
{
return "Green.gif";
}
}

Related

How to databind alt tag in ASP.NET hyperlink control?

I have this tag: alt='<%# Eval("ImageDesc") %>' inside a DataList control
When I view the page in my browser the alt tag is always empty: alt=""
Maybe this is because the alt tag is not supported by the hyperlink control? How can I databind the alt tag?
------- this is the exact code
<asp:HyperLink ID="linkQuoteImage" runat="server" EnableViewState="False" ImageUrl='<%# "/images/"+Eval("ImageFile").ToString().Replace("/","/tmb/") %>' NavigateUrl='<%# "~/Quotes/"+Eval("SlugText") %>' alt='<%# Eval("ImageDesc") %>' Font-Underline="False" ForeColor="#333333"></asp:HyperLink>
if in the aspx page
<asp:HyperLink ID="linkQuoteImage" runat="server">Text for image alt</asp:HyperLink>
If in the code behind just do linkQuoteImage.Text = "Text for image alt" -- The text you need in the alt
Really, the Hyperlink does not have the alt property. Use Tooltip instead, if this is what want:
<asp:HyperLink ID="lnkTest" runat="server" ToolTip='<%# Eval("Data") %>'>'<%# Eval("OtherData")%>'</asp:HyperLink>
The alt property is used in a <img> tag to show a replace text when the image is not found. Also, the text is shown as a tooltip in some browsers. If you want to show a tooltip, use the HTML title property, which can be obtained by using the Tooltip ASP.Net property.
alt attribute is used in hyperlink when we are using basic html
but in case of u r using asp.net hyperlink control alt property is replaced by ToolTip use this instead
replace
alt='<%# Eval("ImageDesc") %>' by ToolTip='<%# Eval("ImageDesc") %>'
Is your <asp:HyperLink> control inside of some control like a Repeater?
This code works for me.
Front end:
<asp:Repeater ID="rptTest" runat="server">
<ItemTemplate>
<asp:HyperLink ID="testLink" runat="server" alt='<%# Eval("ImageDesc") %>'>This is a link</asp:HyperLink>
</ItemTemplate>
</asp:Repeater>
Back end:
protected void Page_Load(object sender, EventArgs e)
{
var images = new List<ImageData>
{
new ImageData { ImageDesc = "test" },
new ImageData { ImageDesc = "test2" }
};
rptTest.DataSource = images;
rptTest.DataBind();
}
...
public class ImageData
{
public string ImageDesc { get; set; }
}
If you aren't using a control that has the Eval method available, then you'll need to add the property differently. I would recommend just setting it in the code-behind.
Front end:
<asp:HyperLink ID="testLink" runat="server">This is a link</asp:HyperLink>
Back end:
protected void Page_Load(object sender, EventArgs e)
{
if (testLink.Attributes["alt"] == null)
{
testLink.Attributes.Add("alt", "test");
}
}

Conditional link in GridView TemplateField with NavigateUrl also conditional ASP.NET 4

I am new to ASP/C# and am trying to create a HyperLink in a GridView Template that will:
a) not display if a database value is NOT true (I have accomplished this)
b) query the SQL database to see if one of two possible fields have values (ISSN or ESSN) - in which case I want to insert that value into a link that queries an external website (PubMed if you are familiar with that).
My ASPX file is:
<asp:TemplateField HeaderText="PubMed">
<ItemTemplate>
<asp:HyperLink ID="lnkPubMed" runat="server" Text="S" Target="_blank" NavigateUrl='<%# Targetlast3Search(Eval("myVar")) %>' Visible='<%# Convert.ToString(Eval("Indexed_NIH")) == "True" ? true : false %>' >
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
Codebehind is:
public string Targetlast3Search(object objlast3Search)
{
Convert.ToString("ISSN");
Convert.ToString("ESSN");
char PubMed = 'http://www.ncbi.nlm.nih.gov/pubmed?term="ISSN"[Journal]%20AND%20%28%22last%203%20years%22[PDat]%29';
if ("ISSN" != null)
{
return (ISSN in URL);
}
else if
{
("ESSN" != null);
{
return (ESSN in URL;
}
}
else
{
return "";
}
}

ASP.NET GridView ItemTemplate

OK I have a GridView and there is a column that I want to be a link if a file exists, otherwise I just want it to be a label. Right now I am changing the controls on RowDataBound event handler using the Row passed in the args. I am not a big fan of this as I am hard coding the column ID, and if it ever changes I will need to remember to change this code. I was hoping I could do a conditional in the asp code to add a link if a property value is not null otherwise add a label. Is this possible? Any different solutions?
I would like something like this:
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<%# if (Eval("LogFileName") == null)
<%#{
<asp:LinkButton ID="LogFileLink" runat="server" CommandArgument='<% #Eval("LogFileName") %>' CommandName="DownloadLogFile" Text='<%# Blah.NDQA.Core.Utilities.GetEnumerationDescription(typeof(Blah.NDQA.Core.BatchStatus), Eval("Status")) %>'>
<%# }
<%# else
<%#{
<asp:Label ID="LogFileLabel" runat="server"Text='<%# Blah.NDQA.Core.Utilities.GetEnumerationDescription(typeof(Blah.NDQA.Core.BatchStatus), Eval("Status")) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
You can continue to use RowDataBound event but in your aspx you add:
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
In your C# code something like that:
if (LogFileName) {
LinkButton ctrl = new LinkButton();
ctrl.CommandArgument= ...;
ctrl.CommandName= ...;
} else {
Label ctrl = new Label();
ctrl.Text= ...;
}
// You have to find the PlaceHolder1
PlaceHolder1.Controls.Add(ctrl);
In this way you don't have to hard coding the column ID
I know this is a little old now but just in case someone else stumbles across this as I did when looking for an answer to a similar question, I found you can do something like this:
<ItemTemplate>
<asp:ImageButton ID="btnDownload" runat="server"
CommandName="Download"
CommandArgument='<%# Eval("Document_ID") & "," & Eval("Document_Name") %>'
ImageUrl="download.png" ToolTip='<%#"Download " & Eval("Document_Name") %>'
Visible='<%# Not(Eval("Document_ID") = -1) %>' />
</ItemTemplate>
i.e. set the Visible property to evaluate a boolean expression based on your field. If you wanted to display something instead of the download link or button, such as a "Not available" label, then you would just set its Visible property to the opposite boolean expression to your download link. (This is VB.NET not C#, but you get the idea.)
If you're going to be doing this a lot, I suggest writing your own field. The simplest approach is probably to make a NullableHyperlinkField inheriting from HyperlinkField, and render out a plain string if the anchor's URL would otherwise be null.
Use properties on the page to determine if you want to show the label or the link
<asp:GridView ID="gv" runat="server">
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:LinkButton runat="server" Visible='<%# ShowLink %>' PostBackUrl="~/Aliases.aspx" >This is the link</asp:LinkButton>
<asp:Label runat="server" Visible='<%# ShowLabel %>'>Aliases label</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The add the properties ShowLink and ShowLable toyour code behind
public bool ShowLabel
{
get
{
//determine if the label should be shown
return false;
}
private set
{
//do nothing
}
}
public bool ShowLink
{
get
{
//determine if the link should be shown
return true;
}
private set
{
//do nothing
}
}

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);
}
}

Get GridView selected row DataKey in Javascript

I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of
function editRecord()
{
var gridView = document.getElementById("<%= GridView.ClientID %>");
var id = // somehow get the id here ???
window.open("edit.aspx?id=" + id);
}
The question is how do I retrieve the selected records ID in javascript?
I worked it out based on JasonS response. What I did was create a hidden field in the Grid View like this:
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("JobID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="False">
<ItemTemplate>
<asp:LinkButton ID="lnkSelect" runat="server" CommandName="select" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
Then on the OnRowDataBind have code to set the selected row
protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Click to highlight row
Control lnkSelect = e.Row.FindControl("lnkSelect");
if (lnkSelect != null)
{
StringBuilder click = new StringBuilder();
click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty));
click.AppendLine(String.Format("onGridViewRowSelected('{0}')", e.Row.RowIndex));
e.Row.Attributes.Add("onclick", click.ToString());
}
}
}
And then in the Javascript I have code like this
<script type="text/javascript">
var selectedRowIndex = null;
function onGridViewRowSelected(rowIndex)
{
selectedRowIndex = rowIndex;
}
function editItem()
{
if (selectedRowIndex == null) return;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0];
var hidID = cell.childNodes[0];
window.open('JobTypeEdit.aspx?id=' + hidID.value);
}
</script>
Works a treat :-)
1) change your javascript function to use a parameter
function editRecord(clientId)
{ ....
2) output the call in your editRecord button... if you want to avoid dealing with the .net generated ids, just use a simple
<input type="button" onclick="editRecord(your-rows-client-id-goes-here)" />
Based off of your comments to #DaveK's response, in javascript you can set the id of a hidden field to the clientId of the selected row when the user selects it. Then have your editRecord function use the value set on the hidden form field.
one could avoid javascript altogether, by setting anchor tags pre-populated with the query string for each row (although this will effect your table layout, it will need only one click rather than 2 from the user)
insert in the gridview template:
<asp:HyperLink runat="server" ID="editLink" Target="_blank"
NavigateURL='<%# Eval("JobID","edit.aspx?id={0}") %>'>
Edit..
</asp:HyperLink>

Resources