I have a gridview column like this:
<asp:TemplateField HeaderText="<%$ Resources:UserProfile, C_Updated %>" ItemStyle-Wrap="false" SortExpression="Updated">
<ItemTemplate>
<asp:Literal ID="UpdatedLiteral" runat="server"
Text='<%# (Eval("Updated").ToString()) == "0" ? string.Format("<span class=greenText>{0}</span>", GetGlobalResourceObject("Vacancies", "VacancyToday")) : ((int)Eval("Updated")) %>' />
<asp:Literal ID="UpdateddaysLiteral" runat="server" Text='<%$ Resources:UserProfile, C_UpdatedDays %>' />
</ItemTemplate>
</asp:TemplateField>
value in updated field is number 0 or greater than 0. but I am getting the error:
CS0173: Type of conditional expression cannot be determined because
there is no implicit conversion between 'string' and 'int'.
Also, I want to show UpdateddaysLiteral only if updated column has value greater than 0. Please suggest how to do this ?
There should be exactly one implicit conversion between b & c in:
var value = a?b:c
This conversion can be in any direction.
What this means is that either b should be implicitly convertible to c or the reverse.
In your case you have b as String and c as Int and there is NO implicit conversion between the two. That's why this error shows up. MSDN may help.
For example, This will also show the same error:
lbldate.Text= (DateTime.Parse(TextBoxActualEndDate.Text)) : null;
So the correction is :( Making any one side convertible to other)
lbldate.Text= (DateTime?)(DateTime.Parse(TextBoxActualEndDate.Text)) : null;
In the last part of your condition:
: ((int)Eval("Updated"))
Why are you casting "Updated" back to int? Just Eval("Updated").ToString() should suffice.
Second part of your question:
<asp:Literal ID="UpdateddaysLiteral" runat="server" Visible='<%# Eval("Updated") > 0 ? "true", "false" %>' ...
Workaround: KISS Principle, that means Keep It Simple Silly.
Why are you making things complicated in your aspx, when you can do it from code behind flawlessly.
Create a method to do your comparison logic on your codebehind. Something like this.
/// This might not be you exact logic, but it will help you
public string comparevalues(string value)
{
if(Convert.ToInt32(value)>0)
{
//do something
}
else
{
// do something else;
}
return result_as_string;
}
In your aspx:
<asp:Literal ID="UpdatedLiteral" runat="server"
Text='<%#comparevalues(Eval("Value_To_Evaluate").ToString() %>' />
Related
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.
All of the dates are becoming empty even if there are dates present in the cell. This is from a gridview template field. I am trying to convert those cells that are not empty but instead, all of them are empty.
asp:Label ID="Label13" runat="server" Text='<%# Eval("assigned_date") != null ? "" : Convert.ToDateTime(Eval("assigned_date")).ToString("MM/dd/yyyy") %>'></asp:Label>
It better to create a function on code behind and call that function - avoid the inline Eval. So the code will be as:
<asp:Label ID="Label13" runat="server" Text='<%# getDateTimeIfExist(Container.DataItem)%>'></asp:Label>
and on code behind
protected string getDateTimeIfExist(object oItem)
{
var DateTimeToRender = DataBinder.Eval(oItem, "assigned_date") as DateTime?;
if (DateTimeToRender != null)
return DateTimeToRender.GetValueOrDefault().ToString("MM/dd/yyyy");
else
return string.Empty;
}
Got it to work by checking for DBNull instead of null
The ? means then
The : mean else
Text='<%# Eval("assigned_date") != DBNull.Value ? Convert.ToDateTime(Eval("assigned_date")).ToString("MM/dd/yyyy") : ""
I have a GridView with two columns and I want to add a third column which will be column A divided by column B. I added a template field but I am getting a divide by zero error. How can I check for zero values to stop the error message?
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCalc" runat="server" >
<%# Convert.ToDecimal(Eval("val1").ToString()) / Convert.ToDecimal(Eval("val2").ToString()) %>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Yes, you sure can. You can even do that inline, but that would clutter your markup too much, so I would suggest moving this code to code behind.
protected decimal Calculate(string a, string b)
{
decimal ad = Convert.ToDecimal(a);
decimal bd = Convert.ToDecimal(bd);
if (bd == 0)
{
return 0; // or whatever
}
return ad / bd;
}
To call this:
<asp:Label ID="lblCalc" runat="server" >
<%# Calculate(Eval("val1").ToString(), Eval("val2").ToString()) %>
</Label>
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" />
i have a gridview, the column has 20 records whose values are in decimal.say like 5686252.345656 i want to trim those value. So that i could see 5686252.34. It would be great if i trim it in the c# code rather in SQL.
Ive binded the values like this..
<asp:TemplateField HeaderText="Weighted Avg" SortExpression="WT_AVG"
ItemStyle-HorizontalAlign="Center" HeaderStyle-VerticalAlign="Top" HeaderStyle-Width="70px">
<ItemTemplate>
<asp:Label ID="lblWT" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"WT_AVG") %>' />
</ItemTemplate>
</asp:TemplateField>
Please help me.
Thanks.
You can apply a format string to the binding statement:
Example:
<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}") %>
I would use Math.Round(decimal d,int decimals) for example
Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.
Math.Round(4.34, 1); // Returns 4.3
Math.Round(4.35, 1); // Returns 4.4
Math.Round(4.36, 1); // Returns 4.4
http://msdn.microsoft.com/en-us/library/zy06z30k(v=vs.100).aspx
EDIT: OR do it in the SQL:
SELECT ROUND(123.9994,3), ROUND(123.9995,3)
returns: 123.9990 124.0000
Rounding on MSDN