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.
Related
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;
}
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 always get values from the database directly to a control like this:
Code-behind:
DataTable table = GetUserInfo();
UserInfo.DataSource = table;
UserInfo.DataBind();
string FirstName = lblFirstName.Text;
string LastName = lblLastName.Text;
DateTime BecomeAMember = DateTime.Parse(lblBecomeAMember.Text);
Markup:
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("FirstName") %>' />
<asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName") %>' />
<asp:Label ID="lblBecomeAMember" runat="server" Text='<%# Eval("BecomeAMember", "{0:dd MMM yyy) %>' />
There has to be a way to use the data in code-behind without putting it to a label and then use String text = label.Text;
I need the minutes and hours from BecomeAMember, and I don't want to use another Label with the full DateTime and make it invisible. It would be nice to know how to get the other values as well.
You may use DataTable methods to read values directly from the table object.
For instance,
string firstName = table.Rows[0]["FirstName"].ToString();
or
foreach (DataRow row in table.Rows)
{
//
}
Or use Select() method to search on specified field.
DataRow[] rows = table.Select("column1='value1'");
Yes, you can directly investigate the data held in the DataTable.
DataTable can be made into an IEnumerable, and can be queried. In your case:
var datetimes = table.AsEnumerable().Select(x => x.Field<DateTime>("BecomeAMember"));
If you really only expect a single row, you can do either:
var dt = table.AsEnumerable().Select(x => x.Field<DateTime>("BecomeAMember")).Single();
or:
var dt = (DateTime) table.Rows[0]["BecomeAMember"];
Then format dt using ToString with a format string.
I would like to run an if statement but the condition uses a variable from the code behind. How do I call that variable? Side note... I am using a gridview and the variable is in a dataset (dsResult - idnbr colum)
<ItemTemplate>
<% string temp = (Eval("idnbr").ToString());
if (temp.Contains("X")) { %>
<asp:Label ID="Label1" runat="server" Text='<%# (Eval("old_amt").ToString(),"ccTot") %>'></asp:Label>
<% } else { %>
<asp:Label ID="Label2" runat="server" Text='<%# (Eval("new_amt").ToString(),"ccTot") %>'></asp:Label>
<% } %>
</ItemTemplate>
Create c# side method that does it for you:
Than use one of 2 ways:
If you deal with well known entity (saying when GridView bound to ObjectDatasource) you
can just cast it to your entity and pass back:
C#:
protected String MySelectorImpl(Object rowData)
{
MyEntity ent = (MyEntity)rowData;
if(ent.idndr .... )
return ....
else
return ...
}
ASP.Net:
<ItemTemplate>
<asp:Label Text='<%# MySelector(Container.DatatItem) %>' ...
Second case - just use eval syntax
C#:
protected string MySelector(Object condition, Object value1, Object value2)
{
if((String)condition ....) return value1.ToString ....
}
ASP.Net:
<ItemTemplate>
<asp:Label Text='<%# MySelector(Container.DatatItem("idnbr", ... %>' ...
(,
I know this doesn't completely answer your question but why not just do this in the code behind? I'm assuming you're doing something with DataBinding?
string temp = (string)DataBinder.Eval(e.Item.DataItem, "idnbr");
string newAmount = (string)DataBinder.Eval(e.Item.DataItem, "new_amt");
string oldAmount = (string)DataBinder.Eval(e.Item.DataItem, "old_amt");
Label lbl1 = e.Item.FindControl("label1") as Label;
if(temp.Contains("X") {
lbl1.Text = oldAmount;
} else {
lbl1.Text = newAmount;
}
You can read from a property that is declared in the code behind; does this satisfy what you want?
Instead of string temp = ..., you can use this.MyProperty.Contains("X")...
<a href="javascript:onclick= window.location = 'RenewalPaymentGateway.aspx?RPID=<%# Eval("RPID")%>'" title="Pay">
<asp:Label ID="TEMP" Text='<%# If(Eval("PaymentStatus").ToString() = "Paid", "View", "Make payment") %>' runat="server" />
here in label the text view will appear when PaymentStatus=paid or the text will be make payment