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) %>' />
Related
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 simple checkBox in Editable gridView :
<asp:TemplateField HeaderText="Editable">
<ItemTemplate>
<asp:Label runat="server" Text="<%# Item.IsEditable %>" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CheckBoxEditable " runat="server" Text="Editable"></asp:CheckBox>
</EditItemTemplate>
</asp:TemplateField>
When I click on edit button in the row, I would like that checkBox is already checked if value is true. (IsEditable is a boolean)
Text Field is easy because I have a BindItem on Text property in EditItemTemplate. But it's not the same for checkBox or dropdownlist
GridView
I use a UpdateItem Method to update my data in database. I tried a small condition to check my checkBox but it does'nt work.
public void GridViewRisquesAggravants_UpdateItem(IndexViewModel item)
{
try
{
if (ModelState.IsValid)
{
CheckBox chbEdit = (CheckBox)GridView.Rows[this.GridView.EditIndex].FindControl("CheckBoxEditable")
if (item.IsEditable)
chbEdit.Checked = true;
new TypeService().Update(new Type
{
IsEditable = item.IsEditable,
});
this.GridView.DataBind();
}
}
catch
{
throw;
}
}
It makes sense because I am not in the right function to declare this. But I just have 3 methods in my webform.
SelectMethod="GridView_GetData"
UpdateMethod="GridView_UpdateItem"
DeleteMethod="GridView_DeleteItem"
Where can I do this?
(And I have the same problem with datas on dropdownList. I don't know where I recover current value during editing)
Thanks in advance
(Sorry I am beginner about webforms and my english is not perfect)
Evy
use the following code instead for checkbox declaration in edit template
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Convert.ToBoolean("true") %>' />
CheckBox chbx = GridView1.HeaderRow.FindControl("CheckBoxEditable") as CheckBox;
if (chbx != null && chbx.Checked)
{
//code here
}
else
{
//else condtion
}
hope this helps
Where can I do this?
Try it in RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chbEdit = (CheckBox)e.Row.FindControl("CheckBoxEditable");
string value = ((Label)e.Row.FindControl("lblID")).Text;
if (value=="True")
chbEdit.Checked = true;
else
chbEdit.Checked = false;
}
}
Note: Don't forget to add OnRowDataBound in GrindView <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" >
I added the property Checked=<%# BindItem.IsEditable %> on CheckBox Control and it works perfectly.
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'm having trouble figuring out how to control the visibility of an image in a gridview based on a session variable.
<asp:Image runat="server" ID="imgImportedData" Width="20px" Height="20px" ImageUrl="~/images/warning.png" CausesValidation="false" />
I tried using Visible='<%# mySessionVariable %>' but I got a message saying mySessionVariable was unavailable. I think this is because it's in a grid because I am using this variable in the code behind for another part of the page outside of the gridview without any problems.
EDIT: I just realized this in a Repeater control and not a GridView.
I tried both of these and still get The name 'MySession' does not exist in the current context
Visible='<%# (bool)MySession.IsImportedData == "true" ? true : false %>'
Visible='<%# MySession.IsImportedData == "true" ? true : false %>'
<%# is a DataBinding ASP server tag. What happens when you change <%# to <%=?
If that doesn't work, I would suggest setting the column's visibility in a RowDataBound event, like so:
MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image imgImportedData = (Image) e.Row.FindControl("imgImportedData");
// Assuming that mySessionVariable isn't already a bool, which it really should be.
imgImportedData.Visible = bool.Parse(mySessionVariable);
}
}
Try this:
<asp:Image runat="server" ID="imgImportedData"
Visible='<%# Session["mySessionVariable"] == "foo" ? true : false %>' />
I got this to work. Thank you for everyone's help. I found an example on this page that helped.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound.aspx
protected void rptAlternateNames_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (e.Item.DataItem != null)
{
Image imageImportedData = ((Image)e.Item.FindControl("imgImportedData"));
if (MySession.IsImportedData)
{
imageImportedData.Visible = true;
}
}
}
}