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") : ""
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.
I want to set visible property of button control from design side using server tag <%# %>. I can do it from code behind in page load method by checking query string mode value like below:
if (!IsPostBack)
{
---
if (Request.QueryString["mode"] != null && Request.QueryString["mode"] == "1")
{
btndelete.Visible = false;
----
}
else if (Request.QueryString["mode"] != null && Request.QueryString["mode"] == "2")
{
btndelete.Visible = true;
----
}
}
Now instead of writing code from code behind i want to check query string mode value from server tag and returned result will be set to Visible property of button.
I have tried this way but No Luck!
<asp:Button ID="btndelete" CausesValidation="false" Text="<%$Resources:General,Delete%>" OnClick="btndelete_Click"
runat="server" CssClass="btnstyle" OnClientClick="showConfirm(this,'mdlAttendanceReportCriteriaDelete'); return false;"
Visible='<%#if(Request.QueryString["mode"].ToString() == "1"){Convert.ToBoolean("false")}else{Convert.ToBoolean("true")} %>'/>
<asp:Button ID="btndelete" CausesValidation="false" Text="<%$Resources:General,Delete%>" OnClick="btndelete_Click"
runat="server" CssClass="btnstyle" OnClientClick="showConfirm(this,'mdlAttendanceReportCriteriaDelete'); return false;"
Visible='<%#(Request.QueryString["mode"].ToString() == "1")?Convert.ToBoolean("false"):Convert.ToBoolean("true") %>'/>
<asp:Button ID="btndelete" CausesValidation="false" Text="<%$Resources:General,Delete%>" OnClick="btndelete_Click"
runat="server" CssClass="btnstyle" OnClientClick="showConfirm(this,'mdlAttendanceReportCriteriaDelete'); return false;"
Visible='<%#!(Request.QueryString["mode"].ToString() == "1") %>'/>
It run without any parser error but there is no effect at all. Can anybody tell me how to achieve this functionality ?! Thanks in advance.
Call DataBind() method in Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
then use this syntax to set the Visible property in aspx code:
Visible='<%# Request.QueryString["mode"] == "2" %>'
What about using
Visible='<% Request.QueryString.Get("mode") == "1"? "true": "false"%>'
or
Visible='<% if (Request.QueryString.Get("mode") == "1" ) "true" else "false" %>'
Visible='<%# Request.QueryString.Get("mode").Equals("1") ? Convert.ToBoolean("False") : Convert.ToBoolean("True") %>'
I need to change values during edit in GridView. I'm using a method Decrypt(object) from codebehind. It works for Eval(), but not work Bind().
<asp:GridView ID="GridView1" runat="server"
DataKeyNames="ID" DataSourceID="entityDataSource1" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTab1" runat="server"
Text='<%# Decrypt(Eval("Name")) %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="lblTab1" runat="server"
Text='<%# Decrypt(Bind("Name")) %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
When I need to do this, I usually set the TextBox Text property on the code behind on the RowDataBound event. It's like this:
protected void GridView1_RowDataBound( Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e ) {
if( e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit ) {
TextBox txt = ( TextBox )e.Row.FindControl( "lblTab1" );
if( txt != null ) {
DataRowView drv = ( DataRowView )e.Row.DataItem;
txt.Text = Decrypt( drv["Name"].ToString() );
}
}
}
For this work, your GridView EditIndex property must be set with your actual index being edited.
Eval() and Bind() are quite different creatures - Eval() is just shorthand for DataBinder.Eval() but Bind() is interpreted by the ASP.NET parser and broken into two parts - one for binding data to the control and the other for moving data from the control to your model.
This is described nicely in this old blog post: How ASP.NET databinding deals with Eval and Bind statements
You don't mention what you are binding to; if you are binding to a business object then you could create a getter/setter property for an un-encrypted Name. Alternatively you could provide an implementation of OnRowUpdating, and perform the Decrypt there. (hint: update the NewValues[] member with the decrypted value).
I have a gridview populated with textbox that can format datetime using this code
<asp:TextBox runat="server" id="txtDateTo"
Text='<%#Convert.ToDateTime(Eval("ByPassDateTo")).ToString("MM/dd/yyyy") %>'
Enabled='<%#(String.IsNullOrEmpty(Eval("ByPassDateTo").ToString())
? true
: false) %>' />
The code is working but the problem I'm facing is that if the textbox.text is populated with null values i get the error
Object cannot be cast from DBNull to other types.
Can someone pls tell me the proper way to do this.. Tnx!
You can use inline if condition same as you use for Enabled.
plz try below code:
<asp:TextBox runat="server" id="txtDateTo" Text='<%# String.IsNullOrEmpty(Eval("ByPassDateTo").ToString()) ? string.Empty : Convert.ToDateTime(Eval("ByPassDateTo")).ToString("MM/dd/yyyy") %>' Enabled='<%#(String.IsNullOrEmpty(Eval("ByPassDateTo").ToString()) ? true: false) %>' />
Thanks
Why don't you use codebehind, in my opinion that's much more readable and maintainable:
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row; // if this doesn't work use the debugger to see the real type
TextBox txtDateTo = (TextBox) e.Row.FindControl("txtDateTo");
DateTime? byPassDateTo = row.Field<DateTime?>("ByPassDateTo");
txtDateTo.Text = byPassDateTo.HasValue ? byPassDateTo.ToShortDateString() : "";
}
}
It's also more efficient and less error-prone due to type safety and compile time check.
You should check whether value retrieved from database is null or not. You can try below code for the textbox :
<asp:TextBox runat="server" id="txtDateTo" Text='<%# Eval("ByPassDateTo") == null ? string.Empty : Convert.ToDateTime(Eval("ByPassDateTo")).ToString("MM/dd/yyyy") %>' Enabled='<%#(String.IsNullOrEmpty(Eval("ByPassDateTo").ToString()) ? true : false) %>' />
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() %>' />