Compare Validator for two dates - asp.net

I have two labels and two text boxes, a Compare validator and a button.
I need it to compare two dates (rental date , return date ) and when the rental date is less or equal to return date are the same. No validation message.
While when when the rental date is less than the return date, display an input error message.
The compare validator has been set with :
controltocompare : txtrental,
controltovalidate: txtreturndate,
operator :greater than equal,
type:date,
errormessage: return date must be greater or equal than rental date,
I am not sure how to get the btn to display it ?

You need to set the property "CausesValidation" of your button to "true" to trigger validation on its click.

Make sure the CompareValidator has runat="server"

Create a method to display message.
private void AlertBox(string Msg)
{
string s = "alert('" + Msg + "')";
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ckey", s, true);
}
find the code to validate and throw alert message.
if (!String.IsNullOrEmpty(txtrental.Text) && !String.IsNullOrEmpty(txtreturndate.Text))
{
DateTime ssSD = Convert.ToDateTime(txtrental.Text);
DateTime qsED = Convert.ToDateTime(txtreturndate.Text);
int chktxtfd1_sd = ssSD.CompareTo(qsSD);
if ((chktxtfd1_sd == 0 || chktxtfd1_sd == -1) )
{
//do something bcoz condition is true
}
else
{
lvflag = false;
AlertBox("date must be greater or equal than rental date");
}
}
If you find it useful, please mark it as your answer else let me know...

Related

Getting error When dt.value length is < 4

I have this code which works fine as long as as dt.Value is different to "int".
This is the line which errors:
(dt.Value.ToLower().Substring(0, 4).Equals("date"))
It works fine if dt.Value is varchar or datetime.
I provided my suggested solution at the end of this post.
// Edit
if (e.CommandName == "Edit")
{
// Get the item
RepeaterItem Item = ((RepeaterItem)((Button)e.CommandSource).NamingContainer);
// Get buttons and repeater
Button savebtn = (Button)(Item.FindControl("btnSave"));
Button editbtn = (Button)(Item.FindControl("btnEdit"));
Repeater rFields = (Repeater)(Item.FindControl("repFields"));
// Enable my fields
foreach (RepeaterItem RI in rFields.Items)
{
// Get data type
HiddenField dt = (HiddenField)(RI.FindControl("hdnDBDataType"));
// Set controls
if (RI.FindControl("chkSetting").Visible) ((CheckBox)RI.FindControl("chkSetting")).Enabled = true;
if (RI.FindControl("ddlSetting").Visible) ((DropDownList)RI.FindControl("ddlSetting")).Enabled = true;
if (RI.FindControl("txtSetting").Visible)
{
((TextBox)RI.FindControl("txtSetting")).Enabled = true;
// Check my data type
if (dt.Value.ToLower().Substring(0, 4).Equals("date")) ((CalendarExtender)RI.FindControl("extDateTime")).Enabled = true;
}
}
}
Is this a good fix ? TIA
if(dt.Value != "int" && dt.Value.ToLower().Substring(0, 4).Equals("date"))
Substring will throw an error if the second parameter is higher than the lenght of the string. What you need to do is check the length before doing the substring or use a method like #Igor suggested in the comments.
Your suggestion to check != "int" is not fullproof if let's say somehow the value is any string less than 4 characters.
(dt.Value.Length > 3 && dt.Value.ToLower().Substring(0, 4).Equals("date"))
I will also put #Igor suggestion here because it is also fullproof:
(dt.Value.StartsWith("date", StringComparison.OrdinalIgnoreCase)

XPages: convert DateTime value to string using browser's locale

A similar question to a previous one I asked, but the difference being that this not for direct rendering from an underlying field - it's instead part of a some SSJS.
This is for a view column which displays the result of a SSJS function, which returns HTML that gets rendered. This HTML includes a date from a DateTime field, which gets converted to text using #Text. The problem I have with this is, #Text converts dates using the locale settings of the server, not the browser.
Is there an alternative to #Text(dateValue,"D0S0") that's browser locale aware?
The most "XPagey" way to do this is to use a date/time converter. For example (using a stand-in for the computed value):
<xp:viewColumn columnName="">
<xp:this.value><![CDATA[#{javascript:
new java.util.Date()
}]]></xp:this.value>
<xp:this.converter>
<xp:convertDateTime type="both"/>
</xp:this.converter>
</xp:viewColumn>
That "convertDateTime", with its built-in formats, will respect the browser's provided locale. If you set the option in the Xsp Properties to use the browser's time zone and "Round trip", it should also respect the user's time zone.
I've managed to get round this by using DateFormat.getDateInstance. The only problem with this is it doesn't return a short date in the same format as the XPage date converter (no leading zeros and a 2-figure year). I've got round this though with some fiddling around with the string after.
Here's the full function:
function returnLocalShortDate(ndtDate) {
// Receives NotesDateTime object, Java date or string; returns localised date string in XPages short date format
importPackage(java.text);
if (#IsText(ndtDate)) { // string
var jsDate = #TextToTime(ndtDate);
} else if (ndtDate instanceof Date) { // Java date
var jsDate:Date = ndtDate;
} else if (#IsTime(ndtDate)) { // Notes date/time
var jsDate:Date = ndtDate[0].toJavaDate();
} else {
return("");
}
var strDate:String = java.text.DateFormat.getDateInstance(DateFormat.SHORT, context.getLocale()).format(jsDate);
var strYear = jsDate.getFullYear();
var strDateArray = strDate.split("/");
strDate = ('0' + strDateArray[0]).slice(-2) + '/' + ('0' + strDateArray[1]).slice(-2) + '/' + strYear;
return(strDate);
}
Actually, if you know the format you want, rather than what the user might want via their browser settings, you should use the SimpleDateFormatter class. You can supply the format in accordance with whatever pattern you want from the javadocs for that class. If you supply the NotesDocument object and the field name, this returns the date in dd-MMM-yyyy format.
function getFormattedDate ( doc:NotesDocument, fieldName:String ) {
importPackage(java.text);
var dateFormatter:java.text.SimpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
var d:Date = new Date(#Today());
if ( doc.hasItem (fieldName) ) {
var valueVector:java.util.Vector = doc.getItemValueDateTimeArray(fieldName);
var iterator = valueVector.iterator();
while (iterator.hasNext()) {
var itemvalue = iterator.next();
if ((typeof(itemvalue)).endsWith("DateTime")) {
d = new Date(itemvalue.toJavaDate());
return dateFormatter.format(d);
}
}
} else {
return fieldName + " is not on the document"
}
}
I owe credit to Declan Lynch's blog entry on date formatting, which takes a little debugging because SSJS returns the date value as an Vector now.

gridview display the text instead of values

my question is:
my table consists of this values: 0, 1, 2 3
but when the gridview loads i want the text to be display instead of just those numbers.
0 = not set, 1 = low, 2 = medium, 3 = high
i could have done this like if/else condition but i just wanted to seek for a optimized sol.
here is my markup gridview:
<asp:TemplateField HeaderText="Priority" SortExpression="Priority" >
<ItemTemplate>
<asp:Label ID="lblPriority" Text='<%# DataBinder.Eval(Container.DataItem,"Priority")%>' runat="server" />
</ItemTemplate>
Assuming you don't have the display values stored in the DB anywhere, this is a way you can implement the rendering part. There may be a more maintainable way to store the lookup values, if anyone could contribute I'd appreciate it.
I wrote this in notepad since I don't have Visual Studio on my machine. Please excuse me if there are any syntax errors.
Markup:
<asp:Label ID="lblPriority" Text='<%# RenderPriority(DataBinder.Eval(Container.DataItem,"Priority")) %>' runat="server" />
Code:
Protected Function RenderPriority(ByVal dbValue As Object) As String
Dim strReturn as String = String.Empty
If Not IsDbNull(dbValue) Then
Dim intValue as Integer
If Integer.TryParse(dbValue, intValue) Then
Select Case intValue
Case 0
strReturn = "not set"
Case 1
strReturn = "low"
Case 2
strReturn = "medium"
Case 3
strReturn = "high"
End Select
Else
strReturn = dbValue.ToString()
End If
End If
Return strReturn
End Function
Edit:
After re-reading your question I get the impression you would prefer to avoid writing a specific function for this purpose in the code-behind page. If that is the case you should probably store the strings you want associated with the key values in the DB and pull them out through your SQL statement. Or, at the very least push the functionality down into a Data Access Layer. Either way ideally the GridView column will be presented with the required string by its datasource.
Why not using enumerations? Here:
Have an enumeration called Priority. Then put Description attribute on each of them, and write the display text inside the constructor of that attribute.
public enum Priority
{
[Description("not set")]
NotSet = 0,
[Description("low")]
Low = 1,
[Description("medium")]
Medium = 2,
[Description("high")]
High = 3
}
Then use Enum.ToObject method to convert the numbers (values) into their associated display value using these functions:
// An extension method for ease of use that converts an integer into enum
public static T ToEnum<T>(this int value)
{
if (typeof(T).BaseType.Name != typeof(Enum).Name)
{
throw new Exception("Input type of generic method ToEnum<T>() is not an Enum");
}
return (T)Enum.ToObject(typeof(T), value);
}
// Another extension method that gets the display text of the Description attribute of a given enum constant
public static string GetDescription(this Enum value)
{
return ((DescriptionAttribute)value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false)[0]).Description;
}
Then in your code, you can write:
databaseValue.ToEnum<Priority>().GetDescription();
You can use the RowDataBound event of the GridView and set the value on specific condition.
Here is the complete code....
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRow dr = ((System.Data.DataRowView)e.Row.DataItem).Row;
if (dr["Priority"].ToString() == "0")
{
((Label)e.Row.FindControl("lblPriority")).Text = "not set";
}
else if (dr["Priority"].ToString() == "1")
{
((Label)e.Row.FindControl("lblPriority")).Text = "low";
}
else if (dr["Priority"].ToString() == "2")
{
((Label)e.Row.FindControl("lblPriority")).Text = "medium";
}
else if (dr["Priority"].ToString() == "3")
{
((Label)e.Row.FindControl("lblPriority")).Text = "high";
}
}
}

checking field values for null

I've been working through this for a while and I'm missing the obvious. I'm trying to make sure that if a textbox value is left blank an error isn't thrown and instead a simple message is displayed in the textbox. However, what I've got and several other methods I've tried similar to this haven't worked. I can't figure out why this isn't working and what I need to do differently.
Basics:
This is a simple calculator that allows one to enter their waist, neck, and height measurements to use in a formula that calculates their estimated body fat percentage. The calculation works properly unless a field is left blank.
Thanks for any help!
My code:
if (TBWaist.Text == null || TBNeck.Text == null || TBHeight.Text == null)
{
TBBodyFat.Text = "Value missing";
}
else
if (TBWaist.Text != null & TBNeck.Text != null & TBHeight.Text != null)
{
double waist;
double neck;
double height;
waist = Convert.ToDouble(TBWaist.Text);
neck = Convert.ToDouble(TBNeck.Text);
height = Convert.ToDouble(TBHeight.Text);
TBBodyFat.Text = Convert.ToString(String.Format("{0:p2}", ((501.5 / (1.0324 - .19077 * (Math.Log10(waist - neck)) + .15456 * (Math.Log10(height))) - 450) / 100)));
Error Message
This is the error message I get if I leave the waist textbox blank. I get the same error if I leave any of the others blank as well.
Input string was not in a correct format on line 45.
waist = Convert.ToDouble(TBWaist.Text);
I would recommend using the TryParse methods. In this way, a blank, an empty string or something that is not convertible to a string are all treated the same. Second, I would recommend adding RequiredFieldValidators and/or RegularExpressionValidators to each of the text boxes to ensure that the user enters a value and that value is numeric. In this way, the check in your event procedure acts as a last ditch check instead of requiring a PostBack for validation
protected void Button1_Click(object sender, EventArgs e)
{
//Navy Men's Body Fat Formula: %Fat=495/(1.0324-.19077(log(abdomen-neck))+.15456(log(height)))-450
//string outputString = String.Format("At loop position {0}.\n", i);
double waist;
double neck;
double height;
if ( !double.TryParse( TBWaist.Text, out waist )
|| !double.TryParse( TBNeck.Text, out neck )
|| !double.TryParse( TBHeight.Text, out height ) )
{
ErrorMessageLabel.Text = "Please ensure that each value entered is numeric.";
return;
}
var bodyFat = (501.5
/ (1.0324 - .19077 * (Math.Log10(waist - neck))
+ .15456 * (Math.Log10(height))
) - 450 ) / 100;
TBBodyFat.Text = bodyFat.ToString("P2");
}
You should test for more than just null values you have to test for empty as well
use String.IsNullOrEmpty(TBWaist.Text);
How about using a RequiredFieldValidator?
Alternatively, you can check that the value is an empty string and/or null
if (
String.IsNullOrEmpty(TBWaist.Text) ||
String.IsNullOrEmpty(TBNeck.Text) ||
String.IsNullOrEmpty(TBHeight.Text)
)
Try a compare like
if( String.IsNullOrEmpty( TBWaist.Text ) == true )
{
// error case
}
else
{
// do stuff
}
You should use String.IsNullOrEmpty() instead. Your input field values are not null, simply empty, hence the conversion fails.
protected void Button1_Click(object sender, EventArgs e)
{
//Navy Men's Body Fat Formula: %Fat=495/(1.0324-.19077(log(abdomen-neck))+.15456(log(height)))-450
//string outputString = String.Format("At loop position {0}.\n", i);
if (String.IsNullOrEmpty(TBWaist.Text) || String.IsNullOrEmpty(TBNeck.Text) || String.IsNullOrEmpty(TBHeight.Text))
{
TBBodyFat.Text = "Value missing";
}
else
{
double waist;
double neck;
double height;
waist = Convert.ToDouble(TBWaist.Text);
neck = Convert.ToDouble(TBNeck.Text);
height = Convert.ToDouble(TBHeight.Text);
TBBodyFat.Text = Convert.ToString(String.Format("{0:p2}", ((501.5 / (1.0324 - .19077 * (Math.Log10(waist - neck)) + .15456 * (Math.Log10(height))) - 450) / 100)));
}
}

Error: FormatException was unhandled by user code in Linq how to solve?

Look please below this codes throw me : FormatException was unhandled by user code
Codes:
satis.KDV = Decimal.Parse((from o in genSatisctx.Urun where o.ID == UrunID select o.Kdv).ToString());
How can i rewrite linq query?
You are calling ToString on the query rather than a single result. Even though you may expect only one value to match your query, it will not return just a single value. You have to instruct it to do so using Single, First, Last or the variations of these that also return a default value (SingleOrDefault, FirstOrDefault, LastOrDefault).
In order to avoid an exception, you could change it to use Decimal.TryParse or you could change your code to use a default value if the LINQ query returns something that won't parse properly. I'd recommend the former or a combination.
Note that in the following example, I have added the call to SingleOrDefault. This ensures that only one value is parsed, even if no value is found, and that if there are multiple results, we get an exception (i.e. it enforces that we get exactly zero or one result to the query).
decimal parsedValue;
if (Decimal.TryParse(
genSatisctx
.Urun
.Where(o => o.ID == UrunID)
.Select(o=>o.Kdv)
.SingleOrDefault()
.ToString(), out parsedValue))
{
satis.KDV = parsedValue;
}
You're calling ToString() on an IQueryable<T> - what did you expect the string to be? It's very unlikely to be anything which can be parsed as a decimal number!
My guess is that you want to call First() or Single(), but we can't really tell without more information. What's the type of o.Kdv?
I suspect you either want:
satis.KDV = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
or
string kdvString = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
decimal kdv;
if (decimal.TryParse(kdvString, out kdv))
{
satis.KDV = kdv;
}
else
{
// What do you want to do if it's not valid?
}
When I use debug mode I see the data is update when over mouse, after end of this method ( it's show this message [input string was not in a correct format]
/* protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
SqlDataSource2.UpdateParameters["Name"].DefaultValue = name.ToString();
TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
SqlDataSource2.UpdateParameters["Age"].DefaultValue = age.ToString();
TextBox birthday = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditBirthday");
SqlDataSource2.UpdateParameters["Birthday"].DefaultValue = birthday.ToString();
DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropEditCountry");
SqlDataSource2.UpdateParameters["CountryID"].DefaultValue = country.SelectedValue;
TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
SqlDataSource2.UpdateParameters["Mobile_No"].DefaultValue = mobile.ToString();
SqlDataSource2.Update();
}
catch (Exception j)
{
j.Message.ToString();
}
}
/* }

Resources