set calendar extender format - asp.net

Does anyone know if there is a way of specifying the Format of a calendar extender with a dynamic value from the aspx?
I tried this but it doesnt seem to set the format at all. Does anyone see anything wrong with it:
<asp:TextBox ID="tbStartDate" runat="server" />
<act:CalendarExtender ID="clndrStartDate" PopupPosition="Right" runat="server"
Format='<%# DefaultDateFormat %>' TargetControlID="tbStartDate"></act:CalendarExtender>
and i have the DefaultDateFormat getter in a base page of the code beheind like this:
public static string DefaultDateFormat
{
get { return "dd/MM/yyyy"; }
}
Any help would be appretiated.
Thank you

Call DataBind Method on calendar extender instance.
clndrStartDate.DataBind();
This solution worked for me.

Don't you mean to say Format="<% =DefaultDateFormat%>" and you may not want DefaultDateFormat to be a static property.
You appear to be missing "" and = in your example. But I could be wrong.

Related

Showing single error for multiple asp validators

I have a text box control in asp with 3 different validators. Each validator is getting its error message from the server, and each one validates different things.
My problem is that for some values, two or more validators are firing and I'm getting more then one error message.
I would like to make some kind of priority functionality, meaning that if the first validator is firing the other two will not. Is there any way to make the validator behave like that?
I've added some code sample:
<asp:RequiredFieldValidator ID="cvRequired" runat="server" Display="Dynamic"
ControlToValidate="txtBox" />
<asp:RegularExpressionValidator ID="cvFormat" runat="server" Display="Dynamic"
ControlToValidate="txtBox" ValidationExpression="^([A-Za-z])+$" />
<asp:CustomValidator ID="cvCustom" runat="server" Display="Dynamic"
ControlToValidate="txtBox" ClientValidationFunction="validateFunction" />
I want that the format validator and the custom validator will not fire if the required validator is invalid (actually, I just want them to not showing their error message).
As I said, the error messages are from the server, so I can't really join them to one custom validator. Also, the "validateFunction" is in another js file (for re-use).
Few logic options you got to think about,
(txtPhone) having three validators.
1.RangeValidator, 2.CustomValidator 3.Regexvalidator
Say,after validation (check what it returns if validation fails/passes) and act upon that.
if(rangevalidator1 != null)
{
...somecode...
}
I ll suggest you using javascript ..
you can use a single custom validator for all three validation and you put your code in if condition according to your need.
<asp:CustomValidator runat="server" ID="cstmStartDateValidater"
ToolTip="Start date cannot be greater than equal to end date/time or less than current date/time"
ErrorMessage="*" ControlToValidate="txtStartDateTime"
ForeColor="Red" ValidationGroup="vlgMessage" SetFocusOnError="true"
onservervalidate="cstmStartDateValidater_ServerValidate" ></asp:CustomValidator>
in the .cs page
protected void cstmStartDateValidater_ServerValidate(object source, ServerValidateEventArgs args)
{
if (CompareStartDate())
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
you can use following link for more information :
MSDN,
Code Project
hope these will help you .
Make use of ValidatorCalloutExtender control which is available in ajax control toolkit.
Place a separate ValidatorCalloutExtender across each control,you wish to validate it.

AjaxControlToolkit AutoCompleteExtender ... how to fill from linq query?

Go easy... I'm a newbie at this.
Ok, I've added the AutoCompleteExtender to my webpage. The user will add search tags to a project, and I want the textbox to autocomplete with tags that already exist in the database.
I don't have a "registry" for tags; only a table with a tagName and a projectID. So, a tagName might be repeated many times in the table. So I just want to return distinct results in my query. (That's easy.)
But how do I tie it to the AutoCompleteExtender? I'm not well versed in WebServices, etc...
I'm using entity framework, fyi...
Here's my autocomplete code on the aspx page:
<asp:TextBox ID="TagNameTextBox" runat="server"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="TagNameTextBox_AutoCompleteExtender"
runat="server"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="2"
EnableCaching="false"
DelimiterCharacters=""
Enabled="True"
TargetControlID="TagNameTextBox">
</ajaxToolkit:AutoCompleteExtender>
And here's my linq query:
var qrygettags = (from t in db.TagTables
select new { t.TagName }).Distinct().ToString();
I found a few examples of a jquery solution, too, but I don't know how to get my query into that format. Any help or ideas would be greatly appreciated!
Well, I kept hunting around and found this seemingly easy solution, and it works for me.
in the aspx page, in the control, I have
ServiceMethod="GetTagNames"
and in the cs page I added this in the page load:
[System.Web.Services.WebMethod]
public static string[] GetTagNames(string prefixText, int count)
{
mydatabase db = new mydatabase();
return db.TagTables.Where(n => n.TagName.StartsWith(prefixText)).OrderBy(n => n.TagName).Select(n => n.TagName).Distinct().Take(count).ToArray();
}
Hopefully it will help someone else out there!

regex validator, required field

I'm trying to use the regular expression validator for a numeric ID field. The field needs to be a required field of any number. Currently, I'm using:
="\d{1,}"
Shouldn't this make it so the user has to at least enter 1 digit?? If I hit the submit button with the field empty, it passes validation and posts back.. But if I enter non-numeric characters, it errors fine. If I wanted zero or more occurrences, I'd use: ="(\d{1,})?"
Why isn't this working? Do I need to use this in combination with a Required Field Validator? That would suck ><
Make sure you set the property ValidateEmptyText to true or else the CustomValidator will not fire for empty text.
EDIT: You can attach a javascript function to the CustomValidator to accomplish this since I don't think a RegularExpressionValidator will fire against an empty control. I have created a basic example to illustrate the solution:
<script type="text/javascript">
function CheckMyText(sender, args) {
var compare = RegExp("\\d{1,}");
args.IsValid = compare.test(args.Value);
return;
}
</script>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:Button ID="btnTest" runat="server" Text="Test" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Error!"
ControlToValidate="txtTest" ValidateEmptyText="true"
ClientValidationFunction="CheckMyText"></asp:CustomValidator>
I have tested it and it seems to work. Leave a comment if you require further assistance.
You still need to use a RequiredFieldValidator.
I'm not sure where the user is entering the IDs, but if the input field is TextBox control why don't you use something like this:
if (tbID.Text.Length != 0)
{
//Logic goes here
}
When user clicks submit, you need to make sure that not only empty strings are captured, below is a regex that looks for any whitespace(tab,space etc) + matches if character is not a digit(0-9)
Dim FoundMatch As Boolean
Try
FoundMatch = Regex.IsMatch(SubjectString, "\Dm/rld$/\s", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
'put your code here
Catch ex As ArgumentException
'syntax error in regular expression
End Try
I believe you'll need to use postback on your page, if you decide to use RequiredFieldValidator you can use above regex expression for that as well
Hth
In case someone is not using a CustomValidator then you can have a RequiredFieldValidator and RegularExpressionValidator for the same control. Found this solution here: http://forums.asp.net/t/1230931.aspx . Normally, this results in the error messages being displaced for the second validator but there is a way to fix that. You just have to set the Display property to dynamic for both the validators. Now the error messages for both the validators are displayed in the same location. Example code:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="ErrorMsg" ControlToValidate="controlID"
ValidationExpression="regexExpression"
Display="Dynamic"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ErrorMessage="ErrorMsg" ControlToValidate="controlID"
Display="Dynamic"></asp:RequiredFieldValidator>`

ASP.NET binding to a UserControl property

This should be really easy but I can't figure out how to make it work...
I have an ASP.NET UserControl (.ascx) with the following property:
public string LabelCssClass
{
get
{
return _labelCssClass;
}
set
{
_labelCssClass = value;
}
}
I want to bind that property into the HTML of the UserControl at run time, using the <%# syntax. I imagine it must be something along these lines:
<td class="<%# Eval("LabelCssClass") %>" >
I've tried all different versions of Eval() and so on ... I'm not getting errors but the binding isn't working, and my breakpoints show that the property is not being accessed.
Whats the correct syntax? cheers
I think what you might want is this:
<td class="<%=LabelCssClass%>">
Kevin's answer is probably closer to what you are trying to achieve; however, you can successfully use the <%# %> syntax in the standard markup if you call DataBind() on the Page itself.

Disable backspace in textbox via javascript

I have a textbox which is extended by an Ajax Control Toolkit calendar.
I want to make it so that the user cannot edit the textbox and will have to instead use the calendar extender for input.
I have managed to block all keys except backspace!
This is what I have so far:
<asp:TextBox ID="TextBox1" runat="server" onKeyPress="javascript: return false;" onKeyDown="javascript: return false;" onPaste="javascript: return false;" />
How would I also disable backspace within the textbox using javascript?
EDIT
Made an edit since I need a solution in javascript.
EDIT
It turns out that onKeyDown="javascript: return false;" DOES work. I have no idea why it wasn't working before. I tried using a new textbox and it blocked backspaces fine. So sorry to everyone who posted an answer hoping to get some rep esp. after I marked it for bounty.
My textboxes now (seem) to block ALL keystrokes and also still work with the calendar extender.
ZX12R was close. This is the correct solution:
The TextBox is like this:
<asp:TextBox ID="TextBox1" runat="server" onKeyDown="preventBackspace();"></asp:TextBox>
and the script looks like this:
<script type="text/javascript">
function preventBackspace(e) {
var evt = e || window.event;
if (evt) {
var keyCode = evt.charCode || evt.keyCode;
if (keyCode === 8) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
}
}
</script>
First of all, the backspace wont come through on Key Press, so you have to use Key Down.
Can't you just use the HTML readonly="readonly" attribute?
<input type="text" name="country" value="Norway" readonly="readonly" />
<textarea rows="3" cols="25" readonly="readonly">
It should work! :)
</textarea>
How about using a label for the display and a hidden textbox to get the value back to the server?
You need to apply readonly on the client side controller ONLY, so that asp.net doesn't see it and still reads the data on postback. You can do this several ways, one of the easier if you use jQuery is to add a class to the text-boxes eg. cssclass="readonly" in question and $(".readonly").attr("readonly", true);.
As others said ReadOnly="True" will break the postback mechanism.
I believe you can get around it in your code-behind by accessing the Request object directly during PageLoad:
//assuming your textbox ID is 'txtDate'
if(Page.IsPostBack)
{
this.txtDate.Text = Request[this.txtDate.UniqueID];
}
Your other option is to allow Disabled controls to postback on the form, but this is somewhat of a security concern as readonly fields modified via script could potentially come back:
<form id="MyForm" runat="server" SubmitDisabledControls="True">
..
</form>
http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.submitdisabledcontrols.aspx
I'm not sure the impact of this property on ReadOnly (vs Enabled="False") controls but it's worth trying.
And finally - I did run into the same issue you're having a few years ago, and from what I remember there is a difference between using an html input marked as readonly and runat="server", and an actual serverside control where ReadOnly="true".
I have a feeling doing:
<input type="text" readonly="readonly" runat="server" id="myTextBox" />
may have still allowed the data to come through, although in the code-behind you have to treat the control as a HtmlInputText or HtmlGenericControl vs. a TextBox. You can still access the properties you need though.
Just a few ideas anyway...
here is a possible solution... add an event listener...
<asp:TextBox ID="TextBox1" runat="server" onKeyPress="KeyCheck;" />
and then the function can be like this..
function KeyCheck(e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
if (KeyID == 8 ) {
alert('no backspaces!!);
}
}
doubt if it has to be onkeypress or onkeyup...
ReadOnly attribute does not help. The backspace still is taking your browser to back page even if your text box is read only..
use regular text boxes not read-only and not Disabled, just use client-side JavaScript to ignore keypresses.
This will ignore all keypress so you will have your READONLY behaviour and it will also ignore the backspace.
<input type="text" value="Your Text Here" onkeydown="return false;" />
No Need to call any function and all just try this:
<asp:TextBox runat="server" ID="txt" onkeydown="return false;"
onpaste = "return false;" onkeypress="return false;" />
I was able to do something similar, with Jquery. Just putting it out here for reference!
$("#inputID").keypress(function (e)
{e.preventDefault();});
$("#inputID").keydown(function (e)
{e.preventDefault();});
the first prevents keypresses, while the second prevents key down events.
Still a JS noob, so feel free to point out good / bad things with this.

Resources