Reputation: 1526
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!
Upvotes: 0
Views: 196
Reputation: 1228
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
Upvotes: 2
Reputation: 460108
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.
Upvotes: 1
Reputation: 10122
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) %>' />
Upvotes: 1