Base on Date visibility condition in HyperLink using asp.net c#. I am not getting how to match the condidation. If EventDate less than today and equal to today date means visible false.
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="http://mysite.in/registerForm.aspx" Visible='<%# Eval("DateofEvent").ToString() <= DateTime.Now %>' Text="Click here for registration" Target="_blank" />
EventDate is like that save in table.
2016-03-29 00:00:00.000
In ASPX:
Visible='<%#GetVisible(Eval("DateofEvent").ToString())%>'
And in the code behind:
public bool GetVisible(object value)
{
if (Convert.ToDateTime(value) <= DateTime.Now)
{
return false;
}
return true;
}
Related
Code on aspx:
<EditItemTemplate>
<asp:TextBox ID="TextBox12" runat="server" Text='<%# Bind("Release_Dt", "{0:yyyy-MM-dd}") %>'></asp:TextBox>
<asp:CustomValidator runat="server" ID="Release_Dt_vdt1"
ControlToValidate="TextBox12" onservervalidate="validate_dt"
ErrorMessage="enter valid date" ValidationGroup="UpdateVdtGrp" ForeColor="Red" Display="Dynamic" SetFocusOnError="true">
</asp:CustomValidator>
</EditItemTemplate>
Validation code (in code behind):
protected void validate_dt(object source, ServerValidateEventArgs args)
{
DateTime minDate = DateTime.Parse("1000/12/28");
DateTime maxDate = DateTime.Parse("9999/12/28");
DateTime dt;
args.IsValid = (DateTime.TryParse(args.Value, out dt)
&& dt <= maxDate
&& dt >= minDate);
}
Question: The date format keeps changing from "yyyy-MM-dd" to short / long date format as shown below every time the row is updated (even just clicking "edit" and "update" on the default gridview buttons without changing any content / dedicated editing 'textbox12'). What is the cause, and how could we fix it?
I have clarify that the SQL database connected to, which this data is stored as string, does not auto-format the data when updated.
If I am missing some piece of important info for the question please advise, thanks in advance.
with asp.net c# I get the code of a country with bind :
<asp:Label runat="server" Text='<%# Bind("h_country") %>' ID="Label1"></asp:Label>
this return code of country like usa, tr, eg, il.
I need to put if conditions and I try to do it like this:
<asp:Label runat="server" Text='<%# if(Bind("h_country")=="usa") resonse.write("United States"); %>' ID="Label1"></asp:Label>
note: I'm using GridView and template.
I tried alo at code behind to get the value of country like this:
String s = Lable1.Text;
but also not workes!
how can I get it as a variable and use if condition ?
You need to use find control if thus label is within the gridview and then get the sting from label.
You probably want to handle this in the code behind
<asp:Label runat="server" Text='<%# GetCountry(Eval("h_country")) %>' ID="Label1"></asp:Label>
code behind
public string GetCountry(object country)
{
if (county.ToString() == "usa")
return "United States";
}
It would be better if you had a lookup so you don't have to have a lot of if statements
This is how you can do conditional checks in the markup while binding. Try something like below but I would not advise doing this kind of conditional checks and response.write at the template level but do it in code behind.
<asp:Label runat="server" Text='<%# Bind("h_country") == "usa" ? "United States" : (string)Bind("h_country") %>' ID="Label1"></asp:Label>
And this is how you can do it at code behind. Use the databound event to find the Label1 and set the appropriate text in there.
You need to define OnRowDataBound="gvTest_DataBound for the gridview in the markup
protected void gvTest_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblCountry = (Label)e.Row.FindControl("Label1");
if (lblCountry.text == "usa"){
// do something here
}
else {
// do something otherwise
}
}
}
I have a control in GridView which converts dateformat From MMddyyyy To ddMMyyyy.
<ItemTemplate>
<asp:Label ID="lblName" runat="server"
Text='<%# Eval("Value1") != DBNull.Value ?
(Convert.ToDateTime(Eval("Value1")).ToString("dd/MM/yyyy")) : Eval("Value1") %>'>
</asp:Label>
</ItemTemplate>
This works perfectly if it gets a date or null value.
But in my case Value1 (the Bind Field) can be a string containing anything. say - 'garbageStr'.
So it fails to convert to date and throws error.
Instead I want to display null or blank value when it fails to convert to DateTime format.
Is there any way to handle this?
you can define a method for this purpose in code behind , and call it, then in method implementation try conversion in DateTime.TryParse and return string accrdingly
In your aspx file:
<asp:Label ID="lblName" runat="server" Text='<%# ReturnPropertDateTime(Eval("Value1")) %>'> </asp:Label>
In your Code Behind file:
protected DateTime ReturnPropertDateTime(object val)
{
DateTime dt = null;
string dateTimeValue = Convert.ToString(val);
DateTime dateTime2;
if (DateTime.TryParse(dateTimeValue.ToString("ddMMyyyy"), out dateTime2))
{
dt = dateTime2;
}
else
{
dt = // Just Assign Default date time value you want.
}
return dt;
}
Although its tedious, but you can make your aspx file more readable through this approach as it prevents clutering and provide flexible handling.
I have the following line of code which evaluates whether the value is true or false, if its true it will show an image if its false it shows a different one.
<itemTemplate>
<img alt="" id="Img1"
src='<%# MyAdmin.GetCheckMark((bool)DataBinder.Eval(Container.DataItem, "ShowImg"))%>'
runat="server" /></ItemTemplate>
Can I customize the Eval part in the back end code in c# and then pass a different variable to it for example in C# I want to do
bool ImgFlag = false;
if(Entity.ShowImg == false && Entity.SomethingElse == true)
{
ImgFlag = true;
}
else if(Entity.ShowImg == false && Entity.SomethingElse == false)
{
ImaFlag = false;
}
else
{
ImgFlag = true;
}
And then I want to use ImgFlag instead of ShowImg in my GridView on each row, so ImgFlag will determine which flag to show..
Or is there a better way?
The issue is that that eval depends now on two things.. not one as before.
Thank you
This does the trick
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Image runat="server" ImageUrlt='<%#(bool)Eval("bit_field")? "first.jpg":"second.jpg" %>'>
</asp:Image>
</ItemTemplate>
Or this
<asp:TemplateField HeaderText="YourField">
<ItemTemplate>
<asp:ImageButton runat="server" ImageUrl="True.jpg" Visible='<%# (bool)Eval("bit_field") %>' />
<asp:ImageButton runat="server" ImageUrl="False.jpg" Visible='<%# !(bool)Eval("bit_field") %>' />
</ItemTemplate>
Found in this question
Eval actually returns a property, so you can just call it twice for different properties.
Kind of
MyAdmin.GetCheckMark2((bool)DataBinder.Eval(Container.DataItem, "ShowImg"),
(bool)DataBinder.Eval(Container.DataItem, "SomethingElse"));
may help
I like to handle and compare a lot of date times in my repeater even I have to work more than one time with the same.
It's a bit ugly, to cast everywhere the Eval("MyDate") like ((DateTime)Eval("MyDate")) to substract 2 datetimes or to compare it, even if you have to do this more than in one operation.
I thought of saving all the evals in a var at start of the repeater?
DateTime mydt1 = Eval("myDate");
DateTime mydt2 = Eval("mydate");
after that, it's easy to do any operations in the whole repeater. Hope you understand my idea. Is this possible? I tried short but everytime errors.
mydt1 - mydt2....
Thank you and best regards.
You could call a method on the code behind page from the repeater using the DateTimes as arguments. The casting logic can be done in the code behind if the goal it to create a cleaner looking aspx page.
Example ASPX:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Literal
ID="Literal1"
runat="server"
Text='<%# DateFoo(Eval("myDate1"), Eval("myDate2")) %>' />
</ItemTemplate>
</asp:Repeater>
Example C# code behind:
protected string DateFoo(Object o1, Object o2)
{
DateTime? dt1 = o1 as DateTime?;
DateTime? dt2 = o2 as DateTime?;
// Do logic with DateTimes
return "string";
}
If you want to add more logic to your repeater I would suggest you move the binding logic to the code behind:
ASPX:
<asp:Repeater id="myRepeater" runat="server">
<ItemTemplate>
<asp:Literal id="myLiteral" runat="server" />
</ItemTemplate>
</asp:Repater>
CS:
protected override void OnInit(EventArgs e)
{
myRepeater.ItemDataBound += myRepeater_ItemDataBound;
base.OnInit(e);
}
void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// this method will be invoked once for every item that is data bound
// this check makes sure you're not in a header or a footer
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// this is the single item being data bound, for instance, a user, if
// the data source is a List<User>
User user = (User) e.Item.DataItem;
// e.Item is your item, here you can find the controls in your template
Literal myLiteral = (Literal) e.Item.FindControl("myLiteral");
myLiteral.Text = user.Username + ", " + user.LastLoginDate.ToShortDateString();
// you can add any amount of logic here
// if you need to use it, e.Item.ItemIndex will tell you what index you're at
}
}
I hate evals with a passion.
This is why I use this code to be rid of them forever and go back to strong typing:
public static class DataItemExtensions
{
public static T As<T>(this IDataItemContainer repeater) where T : class
{
return (T)repeater.DataItem;
}
public static dynamic AsDynamic(this IDataItemContainer repeater)
{
return repeater.DataItem;
}
}
Then use it like this:
<asp:Repeater runat="server" DataSource="<%# this.MyObjectCollection %>">
<ItemTemplate>
<%# Container.As<MyObject>().DateTime %>
</ItemTemplate>
</asp:Repeater>
Note that if you use the Datasource like I did, you need to use this.DataBind() on the page.