Set image width dynamically with Eval in ASP.NET - c#

I have an image in a repeater in ASP.NET. I need to set the width of this image dynamically to a value returned from the database. I get the information from the SQL db, then I bind the repeater to the result set or datasource and I try to specify the width of the image in the repeater as follows:
<asp:Image ID="Image1" runat="server" Width='<%# Eval("ImageSize") %>' ImageUrl="~/Images/ProgressBar.jpg"/>
I get an error stating
Specified cast is not valid.
Could this be caused because of the datatype that is being returned from the db?

Use System.Web.UI.WebControls.Unit.Parse method:
<asp:Image
ID="Image1"
runat="server"
Width='<%# System.Web.UI.WebControls.Unit.Parse(Eval("ImageSize").ToString()) %>'
ImageUrl="~/Images/ProgressBar.jpg"/>

Re-Write in aspx file like this:
Width='<%# ConvertToImageSize(Eval("ImageSize")) %>'
Code-Behind:
protected int ConvertToImageSize(object imageSize)
{
int i = 0;
if (imageSize != null)
{
i = Convert.ToInt32(imageSize);
}
return i;
}
A bit rough but I hope you can do the rest of handling at your end easily.

Related

Display default image or image in bytes in datalist - asp.net

I currently retrieve data from a database and store it in a data list. One of those items is a bytes value that is used to display an image. The code works, however, when there is no image available, I run into an error as a result of trying to perform operations on a null value. Is there any way to to display a default image, such as that found in the imageButton below the one in question, if there is no value in the image field of the database?
<asp:DataList ID="applicationsDataList" runat="server" RepeatColumns="4" OnItemCommand="itemCommand" >
<ItemTemplate>
<table>
<tr>
<td>
<asp:ImageButton ID="userImage" CssClass="cardImage" CommandName="profile" runat="server" ImageUrl='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("image")) %>'/>
<%--<asp:ImageButton CssClass="cardImage" CommandName="profile" runat="server" ImageUrl="/Images/blank.png"/>--%>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
Thanks geniuses!
You can use C#'s ternary operator to check whether the value is null, and insert a base64 string for the default image instead.
Something like this:
ImageUrl='<%# "data:image/jpg;base64," + Eval("image") != null ? Convert.ToBase64String((byte[])Eval("image")) : Convert.ToBase64String(GetDefaultImage()) %>'
That is assuming that Eval("image") is returning null? If possible, it would be ideal to move the call to Eval() outside of the expression so that you don't call it twice (once in the condition, and once in the consequence). You can then define a function like GetDefaultImage() to return a byte array with your default image.
This is what I used to solve the problem in the end :)
ImageUrl='<%# !string.IsNullOrEmpty(Eval("image").ToString()) ? "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("image")) : "/Images/blank.png" %>' />
You could as noted work on a more "complex" expression. But then again?
I often just write code in the on-data bound event.
so, with this:
<asp:ImageButton ID="userImage" CssClass="cardImage" CommandName="profile"
runat="server"/>
Then just put the above in the data bound. It somewhat of a wash out in terms of say having to write a few extra lines of code in item data bound, or having a hard to read messy expression in the markup? (I am open to flipping a coin on this).
But, item data bound then becomes this:
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item
| e.Item.ItemType == ListItemType.AlternatingItem)
{
ImageButton btnImg = (ImageButton)e.Item.FindControl("userImage");
DataRowView rRow = (DataRowView)e.Item.DataItem;
if (DBNull.Value.Equals(rRow["image"]))
btnImg.ImageUrl = "~/Content/ckdelete.png";
else
btnImg.ImageUrl = #"data:image/png;base64,"
+ Convert.ToBase64String((byte[])rRow["image"]);
}
}
Note how we are able to get the data bind row values. That data set ONLY persists during the data binding events - after done, it goes out of scope.

How can I add image into Gridview Databound dynamically using ASP.NET C#

I need to add an image icon to gridview databound at runtime in a specific cell.
I started code already but i'm not sure how to accomplish it because using this code the image don't showing in gridview...
See below:
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.DataItem != null)
{
ImageButton image = new ImageButton();
image.ImageUrl = "C:/inetpub/wwwroot/img/add-page-red.gif";
e.Row.Cells[2].Controls.Add(image);
}
}
Any help would greatly appreciate... Thank you.
// In .aspx page use below code-
//for imageUrl you have to call the method which is defined in code behind-
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Image ID="img" runat="server" ImageUrl='<%# GetImage() %>'/>
</ItemTemplate>
</asp:TemplateField>
// In code behind return the image path-
public static string GetImage()
{
return "../Images/Image.jpg";
}

Can't get Data from Repeater for Function

I wanna put data I got from Repeater ( container.DataItem ) to function as Parameter.
This is what I have tried:
protected String getLink(string CustId)
{
string link = "";
if (Request.QueryString["mode"] != null)
{
link = "~/CustDetails.aspx?id="+CustId;
}
else
{
}
return link;
}
And here's my "HTML"
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<a href='<%# Response.Write(getLink(Eval(Container.DataItem,"CustId")))%>'>
<li><%# DataBinder.Eval(Container.DataItem,"Name")%></li>
You get The best overloaded method match for '' has some invalid arguments error because your function takes string as parameter, and you give it the object - the Eval() function returns an object. You can either use
protected String getLink(object CustId)
and convert it to string later, or the better way:
Response.Write(getLink(Eval(Container.DataItem,"CustId").ToString()))
That way you can keep your function unchanged.
You should use linkbutton inside repeater with
<asp:LinkButton ID ="asd" runat ="server" Text ='<%# DataBinder.Eval(Container.DataItem,"Name")%>' CommandArgument ='<%# Eval(Container.DataItem,"CustId")%>'></asp:LinkButton>
And set the OnItemCommand Property of repeater to call an event like this;
Response.Redirect("~/CustDetails.aspx?id="+Convert.toInt32(e.commandArgument));

ASP.NET <%# Eval("Statement") %> Removes HTML String in Statement?

I'm trying to dynamically populate a table in my ASP.NET webpage from an Azure Storage Table and one of the features I wanted to include is to change the color of the text depending on the value of the element.
I'm using a DataList object which is calling a GetEntries() method to get a list of all the objects to display.
The text in each cell of the table is dynamically displayed using:
<%# Eval("VariableName") %>
So I tried changing the color of the text by doing something like this for each object in the GetEntries() method:
if (condition)
VariableName = "<font color=\"red\">" + VariableName + "</font>";
else
// ...
When I run my program, the text is still black and when I view source, the <font color="red">Bob</font is only Bob.
Does the HTML get stripped when using Eval?
If so, is there an efficient way to change the text color based on the values?
Thanks!
To render as html you can try this:
<asp:Literal Text='<%# Eval("VariableName") %>' Mode="PassThrough" runat="server" />
This requires that you have html (with color info) in VariableName, which may not be pretty.
Alternative 1:
But it will be better if you can add a public property say VariableColor (and leave VariableName unchanged):
public Color VariableColor
{
get
{
return <condition>? Color.Red : Color.Empty;
}
}
and use it like this:
<asp:Label Text='<%# Eval("VariableName") %>' ForeColor='<%# Eval("VariableColor") %>' runat="Server" />
Alternative 2:
Even better could be to create a public bool property (say IsDangerous) which evaluates the condition:
public bool IsDangerous
{
get
{
return <condition>;
}
}
and use it like this:
<asp:Label Text='<%# Eval("VariableName") %>' ForeColor='<%# ((bool)Eval("IsDangerous"))?Color.Red:Color.Empty %>' runat="Server" />

Finding drop down list control from a stored procedure in edit item template of gridview in asp.net c#

I am trying to find a DropDownList control on the EditItemTemplate of a grid view, to populate it with results from a query before it is drawn, but the control is never found.
ddlParent == null
Always!
I may be missing something very obvious but i have tried about 8 different methods to get this find control working, but no matter what i do, it comes up null.
I have included both the ASP and the C#, the sql should not be important as i cant even reach the call!
ASP:
<asp:TemplateField SortExpression="LocationArea2.Name" HeaderText="Parent Location Area">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("LocationArea2.Name") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlParent" runat="server" AppendDataBoundItems="true" DataTextField="LocationArea2.Name"
DataValueField="ParentID" AutoPostBack="false" SelectedValue='<%# Bind("ParentID") %>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
C#:
protected void gvLocationArea_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (gvLocationArea.EditIndex == e.Row.RowIndex)
{
DropDownList ddlParent = (DropDownList)gvLocationArea.Rows[gvLocationArea.EditIndex].FindControl("ddlParent");
if (ddlParent != null)
{
using (SalesSQLEntities db = new SalesSQLEntities())
{
ddlParent.DataSource = db.GetRecursiveAreaList(Convert.ToInt32(((TextBox)gvLocationArea.Rows[gvLocationArea.EditIndex].FindControl("txtLocationAreaID")).Text), true);
ddlParent.DataBind();
ddlParent.Items.Add(new ListItem("* None", ""));
}
}
}
}
I know there is something missing here, the control is just never found no matter what i've tried!
Instead of doing a FindControl, use an offset index of the column in question and get the first control:
(DropDownList)gvLocationArea.Rows[gvLocationArea.EditIndex].Cells[INDEX OF THE DDL].Controls[0]

Categories

Resources