I think if I just show you the following what I'm asking will make sense.
In a link in my aspx, this works:
' title='<%# Container.DataItem["EventTime"].ToString()
But the above contains the date portion of the string.
This does not work (nor does any variant of it):
' title='<%# Container.DataItem["EventTime"].ToString("hh:mm:ss tt",
CultureInfo.InvariantCulture) %>
Evantually, we want the title/hover for the link to read something like "4:30 PM : #Forbes Field"
Everything is working with the exception of the 1/1/1900 being in front of the 4:30
How do I get the date off that EventTime datetime field?
The DataItem indexer returns an object reference, so you can't use DateTime specific methods without casting it. You can also use the String.Format method:
<%# String.Format("{0:hh:mm:ss tt}", Container.DataItem["EventTime"]) %>
Related
I'm trying to create an onclick event like so
onClientClick="document.querySelector('[KPI="31"]').value = '';return false;"
The KPI= value has to be data bound, so I use code like so
onClientClick="<%# document.querySelector('[KPI=Eval("KPI_ID")]').value = '';return false; %>"
But I get an error saying the server code is not well defined. Could anyone help please..
If your datasource is a collection of objects and you are requesting a property called KPI_ID you can avoid using Eval and use Item or Container.DataItem.
Easiest way for me to show this is Container.DataItem, since I don't know what kind of control you are using to bind to. Container.DataItem should be your object, so you only need to cast it to your dataType
onClientClick="document.querySelector('[KPI=<%# ((YourDataType)Container.DataItem).KPI_ID %>)]').value = '';return false;"
If you use a Repeater in .Net 4.5 you can set the ItemType for the Repeater to your DataType so you can replace ((YourDataType)Container.DataItem) to Item:
onClientClick="document.querySelector('[KPI=<%# Item.KPI_ID %>)]').value = '';return false;"
If you are not using a property from an object and KPI_ID is a string to use to get the actual value, e.g. if it's in a DataRow, you have to avoid using " in the whole string, without letting the compiler know that it's not the end of the attribute. You can do that by using ' to indicate start and end of attribute and use string.Format so the single quote ' in your javascript is part of the text and the compiler knows it's not the end of the attribute:
onClientClick='<%# string.Format("document.querySelector('[KPI={0}]').value = '';
return false;", Eval("KPI_ID")) %>'
UPDATE:
To support the the additional double quote you can do:
onClientClick='<%# string.Format("document.querySelector('[KPI=\"{0}\"]').value = '';
return false;", Eval("KPI_ID")) %>'
You can replace Eval("KPI_ID") by Item.KPI_ID or ((YourDataType)Container.DataItem).KPI_ID if you wanna avoid using Eval.
Is it possible in an ASP page to define a variable, then use that variable for a web control's attribute value?
I'm trying to add validation controls to my ASP.NET page, and one of them is a regex control. The expression I want will check that a field only contains numbers, spaces, plus sign and round brackets. (for phone numbers) Now round brackets are a special character that can't be escaped with a slash (as far as I can tell), so what I did was use Regex.Escape() to construct my regular expression, which I stored as a string variable. I now want to use that variable as the value for the regex validation control's expression attribute. Is this possible? If not, how can I achieve the validation I want?
EDIT1: So, in the tag of my ASP page I have this:
<% string PhoneNumber = "[^0-9 |^" + Regex.Escape("(") + " |^" + Regex.Escape(" "); %>
Then further down I have this:
<asp:RegularExpressionValidator ID="MobilePhoneValidator" runat="server" ControlToValidate="MobilePhone" ErrorMessage="Mobile phone number must only contain numbers." ForeColor="Red" ValidationExpression=PhoneNumber></asp:RegularExpressionValidator>
I'm pretty sure that using ValidationExpression="PhoneNumber" will use the actual string PhoneNumber and not look up my variable. Though to be honest, I haven't actually tried that.
I don't know why you spcified a string in markup rather than code behind, but anyway.
Assigning this string to your validator looks like this then:
<asp:RegularExpressionValidator ID="MobilePhoneValidator" runat="server" ControlToValidate="MobilePhone" ErrorMessage="Mobile phone number must only contain numbers." ForeColor="Red" ></asp:RegularExpressionValidator>
<% string PhoneNumber = "[^0-9 |^" + Regex.Escape("(") + " |^" + Regex.Escape(" ");
MobilePhoneValidator.ValidationExpression = PhoneNumber; %>
Or you could just define it in your code file, rather then markup.
I am working on web application using asp.net with vb code.
I have a textbox for time field for which i am using regular expression validator.
the format i want is HH:MM am. the regular expression i am using is "(0[1-9]|[1][0-2])[:]" + "(0[0-9]|[1-5][0-9])[ ][A|a|P|p][M|m]"
i am entering the time example: 08:30 AM or 08:30 PM but the regular expression is showing error message.
Can anyone help me with correct regular expression.
thankyou all in advance
shubha
Use RegularExpressionValidator and below ValidationExpression. I have used that.
ValidationExpression="^(1[0-2]|0[1-9]):[0-5][0-9]\040(AM|am|PM|pm)$"
You don't need to use regular expressions, use DateTime.TryParse or DateTime.TryParseExact instead. I recommend using the regular TryParse method because it affords your visitors flexibility in their formats (e.g. some visitors might want to use the 24-hour system, whereas others can use the 12-hour system).
String input;
DateTime dt;
if( !DateTime.TryParse( input, CultureInfo.InvariantCulture /* change if appropriate */, DateTimeStyles.None, out dt ) ) {
// show error message
}
Now as you're using a validator, you'll want to wrap up this logic in a Validator subclass, but it's really easy:
public class DateTimeValidator : BaseValidator {
protected override bool EvaluateIsValid() {
String controlValidationValue = base.GetControlValidationValue(base.ControlToValidate);
if( String.IsNullOrEmpty( controlValidationValue ) ) return true;
DateTime dt;
return DateTime.TryParse( input, CultureInfo.InvariantCulture /* change if appropriate */, DateTimeStyles.None, out dt );
}
}
Then (assuming you've registered a tag-prefix in web.config) all you need to do is this:
<label>
Enter a valid date/time value.
<input type="text" runat="server" id="someDate" />
<myprefix:DateTimeValidator runat="server" controlToValidate="someDate" />
</label>
You will need a separate <asp:RequiredFieldValidator> if you want the field to be required.
i have an asp,net textbox like this
<asp:TextBox readonly="true" ID="txtLastService" runat="server"></asp:TextBox>
when i tried to get its value to a date variable LastService in code behind, i get this error
Conversion from string "" to type 'Date' is not valid.
Exception
Details: System.InvalidCastException: Conversion from string "" to
type 'Date' is not valid.
Source Error: Line 26: oItem.LastService = txtLastService.Text Source File: .\admin\vehicle\add.aspx.vb Line:
26
i have used this same code in other pages, and it works fine, except for this page
any help
EDIt
Please note that the value of the textbox is not empty when i click submit on the form. And also when i remove the readonly attributes, i don;t get the error. But i need this textbox to be readonly since am using javascript to select date and setting its value
Instead of Readonly="true", try using Enabled="false"
The error seems extremely self-explanatory to me. The string is "" and you are trying to convert it to a Date. So how the heck can an empty string be converted to a Date? What date would that be?
Why not use a HiddenField instead?
<asp:hiddenfield id="txtLastService" runat="server"/>
Try using Request.Form[txtLastService.UniqueID] if C# and
Request.Form(txtLastService.UniqueID) if vb.net
I want to convert string date to system datetime in C#. The user enters date through textbox and it should be converted as to datetime. I trid following code but its not working...
DateTime ToDate = Convert.ToDateTime(txtToDate.Text);
DateTime FromDate = DateTime.Parse(txtFromDate.Text);
It shows the following exception
"String was not recognized as a valid DateTime."
How to do this...???
You could use DateTime.ParseExact(). That way you can specify the format of the input string, so it will be parsed correctly, for example:
dateString = "Sun 15 Jun 2008";
format = "ddd dd MMM yyyy";
try
{
DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture);
}
catch (FormatException)
{
}
whatever user enters in your textbox that should be in valid date format, otherwise write your own function to make it in valid format. then Convert it into DateTime format .
for different format you can check this :
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
for more help you can check similar question on this site :
Validate a DateTime in C#
You can of course parse the user's input and rely on the users to always enter a correct date. But I'd recommend to use a specific control for entering a date, such as the calendar control of the ajax control toolkit.
By using such a control, you can prevent invalid input and it's also much easier for the user. If you search for DatePicker or similar, I'm sure you can find lot's of other similar controls.
Ask the user to enter his datetime in a particular format into textbox i.e., either "ddMMyyyyhhmmss" or "dd/MM/yyyy hh:mm:ss tt" or "dd-MM-yyyy hh:mm:ss tt" or some other formats and use the help of following code to convert in to a Valid datetime.
DateTime ToDate = DateTime.ParseExact(txtToDate.Text, <User DateTime format as String>,
System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
Instead, if the above coding makes complicated then you can try DateTime.TryParse() also
First of all you have to validate text box value that it is valid or not, you can use ajax MaskeditExtender control for that and restrict the use enter only require date formate.
DateTime dt = Convert.ToDateTime(date);
here date is in string.