Default image not shown in ASP ImageField - c#

In my asp.net gridview there's an ASP ImageField,When image is not shown or broken I need to show the Default Image, here I use NullImageUrl for this but this won't work.
My Code:
<asp:ImageField DataImageUrlField="FilePath" ControlStyle-Height="50" ControlStyle-Width="50" HeaderText="Image Preview" NullImageUrl="~/images/Defaultimg.png" />

Gridview Image Tag
<asp:Image class="fbimgsize" ImageUrl='<%# FormatURL(Convert.ToString(DataBinder.Eval(Container.DataItem, "picture"))) %>'
runat="server" ID="imgUser" />
C# Code:
public string FormatURL(string img)
{
try
{
if (Path.GetExtension(img).Equals(".jpg", StringComparison.InvariantCultureIgnoreCase))
{
return img;
}
else
{
return "images/noimage.jpg";
}
}
catch (Exception)
{
return "images/noimage.jpg";
}
}

The solution of #KarthikManoharan does work for local images. However, if you need to keep the ImageFields or need to check remote images, too, you have to add a few lines of javascript to your code. The NullImageUrl property is taken into account only when the corresponding bound datafield is null. It does not check whether or not the image url is valid.
To fix your broken URL's you could do this:
<asp:GridView runat="server" ID="mySuperGridView">
<Columns>
<asp:ImageField DataImageUrlField="ImageUrl" HeaderText="Image Preview" NullImageUrl="~/images/replacement.jpg" />
</Columns>
</asp:GridView>
$(function() {
$("#mySuperGridView").find("img").error(brokenImageHandler);
});
function brokenImageHandler(image, param1) {
$(image.target).attr("src", "images/replacement.jpg");
}
Keep in mind that this function would replace all broken images in your gridview. If you want your ImageFields considered solely you need to a custom attribute to your ImageFields. This can be done in the RowDataBound event of the gridview.

Related

Set User Controls Objects Properties inside a GridView ASP.NET

I insert three template columns in my gridview. In every column I insert a user control. For example in first column there is a user control containing an image and three labels.
In my page load, I need to get list of images in a folder and create a row for each of them. Then I need to update those user controls' images in gridview columns.
Here is the sample code which gets the list of images and will be the data source of GridView:
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Resources/Pictures"));
GridView1.DataSource = filePaths;
GridView1.DataBind();
In this step I can see 4 rows which have filled with RAW user controls (Empty images in image control,default text for labels etc.) Now I need to update each of them with my own properties.
Here is a picture Of my output:
As you can see in first column there are some controls (Image and Labels) which is for user control that I used them in column template of my gridview. But they are RAW and I need to update them. For example I need to update the image with the link you see in the third column.
and Here is a part of my GridView Code:
<asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" Caption="Image List" CellPadding="2" ForeColor="Black" GridLines="None" Height="222px" Width="409px">
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:TemplateField HeaderText="Old Picture">
<ItemTemplate>
<uc1:ImageColumn ID="ImageColumn1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="New Picture">
<ItemTemplate>
<uc2:ReplaceColumn ID="ReplaceColumn1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Allow Access">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Hope it is clear enough. can any one help please?
You have to add public properties to your user controls which you then set using "normal" data-binding expressions. E.g:
user control:
public class MyUserControl : UserControl
{
public string ImageName {get; set;}
}
grid's template column:
<asp:TemplateField ...>
<ItemTemplate>
<uc1:MyUserControl runat="server" ImageName='<%# Eval("ImageUrl")%>' ... />
code-behind:
public class ImageVM { // view-model for data-binding
public string ImageUrl { get; set; }
}
...
var images = LoadImages(); // returns a list of ImageVM instances
grid.DataSource = images;
grid.DataBind();

FindControl recursive - error when finding my FileUpload control in GridView

I have been trying the whole day to fix this, hope someone can give me an answer!
(please keep in mind I'm a beginner in this coding).
I have a database where one of the fields is an imageurl. I have to be able to update this field and thought that I could do so using a GridView with an UpdateItemTemplate.
I soon found out that you have to use the FindControl recursive method to do so - so I implemented the code and I'm now stuck with another error.
I think I know why the error appears, but have no idea how to fix it. It seems that in the tools.cs file the identifier of the control is set to be of data type String, but I have no clue what to do with a FileUpload.
Here is the error message:
cannot convert from 'System.Web.UI.WebControls.FileUpload' to 'string'
ASP.NET GridView control:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="DrinkCategoryID" DataSourceID="ObjectDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="DrinkCategoryID" HeaderText="DrinkCategoryID"
InsertVisible="False" ReadOnly="True" SortExpression="DrinkCategoryID" />
<asp:TemplateField HeaderText="DrinksCategoryName"
SortExpression="DrinksCategoryName">
<EditItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("DrinksCategoryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The tool (FindControl)
public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
And code behind for the web form (click event for the save button)
protected void btnGem_Click(object sender, EventArgs e)
{
FileUpload FileUpload1 = (FileUpload)Tools.FindControlRecursive(
GridView1, FileUpload1);
//This seems to work fine
TextBox txtBox = (TextBox)Tools.FindControlRecursive(GridView1, txtBox.Text);
}
On the first line of your button handler, you're passing the control itself as the second parameter of FindControlRecursive - you need to pass in the string ID of the control you're looking for. In other words:
protected void btnGem_Click(object sender, EventArgs e)
{
FileUpload FileUpload1 = (FileUpload)Tools.FindControlRecursive(GridView1, "FileUpload1");
TextBox txtBox = (TextBox)Tools.FindControlRecursive(GridView1, txtBox.Text); //This seems to work fine
}

ASP:Imagebutton fail to post back in gridview

<asp:GridView ID="gv1" runat="server" Width="100%" DataSourceID="ods1" AutoGenerateColumns="false"
DataKeyNames="FileID" HeaderStyle-Height="20px">
<Columns>
<asp:TemplateField ItemStyle-Width="25px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="imgMimeType" runat="server" CommandName="download" />
</ItemTemplate>
...
I have defined my image button as above, but for some reason row command fails to fire off when I click the button.
Strangely, linkbutton in another column works just fine.
How do I make it so that image button will fire off post back?
Row bind
Image Button imb = e.Row.FindControl("imgMimeType") as ImageButton;
if (imb != null)
{
imb.CommandArgument = file.FileID.ToString();
imb.AlternateText = imb.ToolTip = file.MimeType;
if (file.MimeType.Contains("zip"))
{
imb.ImageUrl = "~/Images/mimetypes/zip-icon.png";
}
...
Row command code
public void gv1_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "download":
...
Try changing the imagebutton to a linkbutton temporarily just to see if it works. It's been a little since I've worked with asp.net but I remember running into an issue where events were not working on ImageButtons missing their images on certain browsers only. Does your ImageButton have an image set?
Add CausesValidation="False" to the imagebutton.
That worked for me.

Display image based on a value in asp GridView column

I have a gridview and one of the template fields is an asp image server tag. I want to display an image in this gridview but based on the value that I obtain on databind.
So, every row can have a different values and based on these values I need to display different images. I tried to call a javascript function GetImage() and pass the value that I obtain on databind to this function. But, I cannot get this to work.
<Columns>
<asp:TemplateField HeaderText="<%$Resources:LocalizedText,LabelStatus%>">
<ItemTemplate>
<asp:Image ID="imgStatus" runat="server" CssClass="label" src="GetImage(<%#Eval(<%# Bind("Status_value") %>) %>)"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Javascript function -
function GetImage(value)
{
if (value == 1)
{
return "../Images/act_green.gif";
}
else
{
return "../Images/act_red.gif";
}
}
What am I doing wrong here? And, how can I fix it? Thanks
Unless you have more needs that you haven't mentioned, there is no need to use Javascript and you might as well do everything on the server.
Change your asp:image tag to the following:
<asp:Image ID="imgStatus" runat="server" CssClass="label" ImageURL='<%# GetImage((int)Eval("Status_Value")) %>' />
In your code-behind, place the following:
public static string GetImage(int value)
{
if (value == 1)
{
return "../Images/act_green.gif";
}
else
{
return "../Images/act_red.jpg";
}
}
And you're done.
Your GetImage function is not executed.
See:
IMG SRC tags and JavaScript
Server side code can return the path to the image without using JS.

Retrieve a TextBox using JavaScript

I have a GirdView in Edit Mode with inside a TextBox.
I need to Retrieve this TextBox with ID (from the source code in the browser) in JavaScript.
ctl00$MainContent$uxListOptions$ctl02$uxValueInput
But I receive an error because my JavaScript is not able to find the TextBox.
Here is the code:
<span onclick="encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')">
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="[Publish]" />
</span>
In my control’s OnPageLoad I call this:
private void addEditorJavaScript()
{
// create our HTML encoder javascript function
// this way it shows up once per page that the control is on
string scr = #"<script type='text/javascript'>function encodeMyHtml(name){
var content = document.getElementById(name).value
content = content.replace(/</g,'<');
content = content.replace(/>/g,'>');
document.getElementById(name).value = content;
}</script>";
// add the javascript into the Page
ClientScriptManager cm = Page.ClientScript;
cm.RegisterClientScriptBlock(this.GetType(), "GlobalJavascript", scr);
}
I am trying to use this code http://dustyreagan.com/how-to-submit-html-without-disabling/
Any Idea what am I doing wrong? Thanks guys!
If you are using ASP.Net 4.0, you could use ClientIdMode=Static or Predictable for this control.
encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')
This will result in
encodeMyHtml('ctl00_MainContent_uxListOptions_ctl02_uxValueInput_FormViewContentManager_ContentTextBox')
Does a control of that ID exist in your DOM?
It seems that you're making a lot of assumptions as to how the ID's will be created. It would be better to immediately reference the ContentTextBox.ClientID.
Something like the following, provided that ContentTextBox is a valid reference to the text box:
encodeMyHtml('<%# ContentTextBox.ClientID %>')
You can define your grid like this :
<div>
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Calibri"
Font-Size = "12pt" HeaderStyle-BackColor = "LightYellow" AllowPaging ="true" ShowFooter = "true" OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" CssClass="css1 mycss" Text='<%# Eval("Period")%>'
onblur="SetPostingPeriod(this)"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</div>
And your Javascript Function Would be :
<script language="javascript" type="text/javascript">
/* Populating same data to all the textboxes inside grid,
once change of text for one textbox - by using jquery
*/
function SetPostingPeriod(obj) {
var cntNbr = $("#" + obj.id).val();
// var cntNbr = document.getElementById(obj.id).value;
// alert(cntNbr);
//Access Grid element by using name selector
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
});
}
</script>
This Javascript function is called onblur event of the textbox.
When this function is called at the same time it passes a parameter
which is nothing but the textbox id.
Inside javascript function by using the parameter which is the
id of the textbox we are getting the vaue.
Here is the code :
var cntNbr = $("#" + obj.id).val();
Then For each of the "txtPeriod" controls available inside the grid, we need to assign
the value of current "txtPeriod" textbox value to them.
Looping Grid to identify each "txtPeriod" available :
Here is the code :
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
});
Inside this loop we need to assign the "txtPeriod"(current/Modified) value to other
"txtPeriod" textboxes.Before assign its good practice to check is it null or NAN.
Here is the code :
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}

Categories