Display image based on a value in asp GridView column - c#

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.

Related

asp.net c# using if conditions with Bind

with asp.net c# I get the code of a country with bind :
<asp:Label runat="server" Text='<%# Bind("h_country") %>' ID="Label1"></asp:Label>
this return code of country like usa, tr, eg, il.
I need to put if conditions and I try to do it like this:
<asp:Label runat="server" Text='<%# if(Bind("h_country")=="usa") resonse.write("United States"); %>' ID="Label1"></asp:Label>
note: I'm using GridView and template.
I tried alo at code behind to get the value of country like this:
String s = Lable1.Text;
but also not workes!
how can I get it as a variable and use if condition ?
You need to use find control if thus label is within the gridview and then get the sting from label.
You probably want to handle this in the code behind
<asp:Label runat="server" Text='<%# GetCountry(Eval("h_country")) %>' ID="Label1"></asp:Label>
code behind
public string GetCountry(object country)
{
if (county.ToString() == "usa")
return "United States";
}
It would be better if you had a lookup so you don't have to have a lot of if statements
This is how you can do conditional checks in the markup while binding. Try something like below but I would not advise doing this kind of conditional checks and response.write at the template level but do it in code behind.
<asp:Label runat="server" Text='<%# Bind("h_country") == "usa" ? "United States" : (string)Bind("h_country") %>' ID="Label1"></asp:Label>
And this is how you can do it at code behind. Use the databound event to find the Label1 and set the appropriate text in there.
You need to define OnRowDataBound="gvTest_DataBound for the gridview in the markup
protected void gvTest_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblCountry = (Label)e.Row.FindControl("Label1");
if (lblCountry.text == "usa"){
// do something here
}
else {
// do something otherwise
}
}
}

Default image not shown in ASP ImageField

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.

Unable to get ID for a asp:dropdownlist which gets populated dynamically

I have an unbound list that gets populated.
<asp:DropDownList ID="ddlState" runat="server" style="margin-left: 81px"
onselectedindexchanged="ddlState_SelectedIndexChanged"
CssClass="styled-select">
</asp:DropDownList>
<asp:DropDownList ID="ddlManagerName" runat="server" Height="22px"
style="margin-left: 08px; width:auto;" ></asp:DropDownList>
and a javascript that runs to get the id on a button click
function validateDynamic() {
var getState = document.getElementById('<%=ddlState.ClientID %>').selectedIndex;
var getManager = document.getElementById('<%=ddlManagerName.ClientID %>').selectedIndex;
if(getState == 0)
{
alert("State is a required field !");
}
if(getManager == 0)
{
alert("Manager Name is a required field !");
}
return false;
}
I have tried most using the following from view source
name="ctl00$MainContent$ddlState" id="MainContent_ddlState" both name and id and all i get is object undefined.
Here is the button code that gets calls the function
<asp:Button id="btnSaveTM" runat="server" Text="Add Team Member" class="btn" onmouseover="this.className='btn btnhov'"
onmouseout="this.className='btn'" style=" Height:34px" OnClientClick="validateDynamic();"
onclick="btnSaveTM_Click" UseSubmitBehavior="true" CausesValidation="true" />
and when I debug, I get getState and manager as undefined. Any help is appreciated.
Use this to get the selected value of DropdownList:
var getState = (document.getElementById('<%= ddlState.ClientID %>')
.options[document.getElementById("<%=ddlState.ClientID%>")
.selectedIndex].value)
Have you looked at the sourcecode returned by the server? Does the ID in the script match the ID of the rendered element? Also code nuggets like <%=ddlState.ClientID %> don't work in an external script file. To get them to work you have to embed the script on the page. They only work with .aspx files.
Also you could try to get the element on the console (like Chrome DevTools). If you the right element is returned you can compare it with the line in your script.

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

Convert Gridview column from ID to String in ItemTemplate

I currently have a Gridview that displays
TypeID , Name , Description.
I would like to display the actual type name instead of the TypeID in the gridview. I created this function that takes in the ID and returns the Name but I am having trouble using it. There are 15-20 different types so How do I convert the TypeID to a Type Name so that it is displayed when the Gridview is rendered.
protected string GetGenericTypeByID(int genericTypeID)
{
string genericTypeName;
GenericType.Generic_TypeDataTable genericTypeNameDS = new GenericType.Generic_TypeDataTable();
genericTypeNameDS = GenericBO.Get_GenericTypeByID(genericTypeID);
genericTypeName = genericTypeNameDS[0]["Generic_Type_Name"].ToString();
return genericTypeName;
}
I thought I would be able to use the function in the ItemTemplate but it seems to be harder that I thought
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("GetGenericTypeByID("Generic_Type_ID")")%>'></asp:Label>
</ItemTemplate>
Thanks to Everyone who helped me solve this problem.
I ended up using the method below and it works perfectly.
GetGenericTypeByID( Convert.ToInt32(Eval("Generic_Type_ID")))
You've got the 'bind/eval' and method call inside out.
See Using Method inside a DataGrid or GridView TemplateField
<asp:TemplateField HeaderText=”Name”>
<ItemTemplate>
<a href='<%# FormatUrl(Eval(”email1″).ToString())%>'><%# Eval(”fname”) %>, <%# Eval(”lname”) %></a>
</ItemTemplate>
With the 'FormatUrl' function being:
public string FormatUrl(string email)
{
return “mailto:” + email;
}
Are you limited to a label tag? If not, Expanding on David HAust's answer try the following:
<ItemTemplate>
<%#GetGenericTypeByID(Eval(Generic_Type_ID))%>
</ItemTemplate>
Create a read-only property on the row class that you're using to populate the grid, and get this property to return the results of your function.

Categories