Wednesday, March 28, 2012

Changing focus when date selected in CalendarExtender control

This may fall more within the realm of general ASP.NET web development, but since it's regarding an AJAX Control Toolkit control, I thought it'd be best posted here.

I'm finding a "feature" of the calendar extender behavior to be be quite annoying. It seems that by default when a date is selected on the calendar and the selected date displays in the associated textbox, the calendar itself stays displayed and the only way I've found to get rid of it is to click anywhere outside the calendar itself. You can't tab out of it to the next textbox, Enter won't get rid of it, etc.

I'm sure there's a way to have the calendar collapse when the date is changed, but I just don't know how - could someone provide a way to do this?

Here's the code for my calendarextender:

<asp:TemplateField HeaderText="Date"><ItemTemplate><asp:Label ID="lblWeatherDate" runat="server" Text='<%# Bind("WeatherDate", "{0:dd-mm-yyyy}")%>' /></ItemTemplate><EditItemTemplate><%-- OnTextChanged="txtWeatherDate_OnTextChanged" --%><asp:TextBox ID="txtWeatherDate" Text='<%# Bind("WeatherDate")%>' runat="server"TabIndex="0" Width="80px" Font-Size="10px" /><ajaxToolkit:MaskedEditExtender ID="editExtWeatherDate" runat="server" TargetControlID="txtWeatherDate" Mask="99/99/9999" MaskType="Date" MessageValidatorTip="True" OnFocusCssClass="MaskedEditFocus" OnInvalidCssClass="MaskedEditError" ErrorTooltipEnabled="True" /><ajaxToolkit:MaskedEditValidator ID="editValidatorWeatherDate" runat="server" ControlExtender="editExtWeatherDate" ControlToValidate="txtWeatherDate" IsValidEmpty="True" InvalidValueMessage="Invalid entry. Select a date from the calendar or enter the format "mm\dd\yyyy"" Display="Dynamic" InvalidValueBlurredMessage="Error" /><ajaxToolkit:CalendarExtender ID="calExtWeatherDate" runat="server" Enabled="True" TargetControlID="txtWeatherDate" Format="MM/dd/yyyy" /></EditItemTemplate></asp:TemplateField>

As you can see I tried messing with the OnTextChanged of the textbox and started up with this code:

Sub txtWeatherDate_TextChanged(ByVal senderAs Object,ByVal eAs EventArgs)Handles txtWeatherDate.TextChangedDim txtWeatherDateAs TextBox =Me.gvWeather.FindControl("txtWeatherDate")txtWeatherDate.End Sub

But I couldn't figure out where to go with that. I was looking for something to do with changing the focus of the textbox, but couldn't figure that out.

Any help would be greatly appreciated.

Thanks!

this is in c# but this is how i get the calendar extender to close on date click

to close the calendar onClick i set this up in the code behind

//Hide the calendarprotected override void OnLoad(EventArgs e) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"hideCalendar", @."function hideCalendar(cb) { cb.hide(); }",true);base.OnLoad(e); }

and this is what the asp code looks like

 <cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" OnClientDateSelectionChanged='hideCalendar'>

Hey, keyboardcowboy

Thanks for the code. It was pretty much a copy-paste thing. The C# converted nicely in a code converter. After selecting the date, the calendar disappears, as it should.

However, the oddest thing is happening now: The date displays in the date label as "dd-00-yyyy". I.e. the proper date number,two zeros for the month, then the proper year. This is regardless of what formatting I use for either the extender or the textbox (I was usingFormat="MM/dd/yyyy" in the extender). The date in the sql table it's coming from is correct and the date can be changed and saved (this is in a gridview) properly and it is even displayed properly when the textbox is showing while the gridview is in edit mode. It's just messed up in the label.

I was using the following for the bound text value for the date label:Text='<%# Bind("WeatherDate", "{0:dd-mm-yyyy}")%>'.When I remove the formatting string the date displays properly, but with the time as well. I can't get the date formatted to mm-dd-yyyy now!

Any thoughts?

Thanks


Okay, I caught one thing I was doing wrong: I was using two different formats: dd-mm-yyyy in the label and mm-dd-yyyy in the textbox.

But unfortunately, getting those two to the same format didn't fix the display problem. It's still displaying the month as two zeros (00). And that's regardless of whether I set the format as dd-mm-yyyy or mm-dd-yyyy.

Weird...


weird. maybe if that format string you are trying doesnt work you can try this .ToShortDateString(); that will display a date but without the time. it works in c# in sure it does in vb also so try this (not sure if it will work because i think casting types is different in vb)

Text='<% # ((DateTime)Bind("WeatherDate")).ToShortDateString()%>'


Yeah - I tried just putting it in my label, but got a build error, saying "DateTime" is a type and cannot be used as an expression. I don't know quite enough to know how to change it to work for my VB code.


Okay - found out CDate is used for casting dates. But I can't find quite the right syntax. I've tried: Text='<%# Bind(CDate("WeatherDate")).ToShortDateString() %>' , and Text='<%# CDate(Bind("WeatherDate")).ToShortDateString() %>' and even Text='<%# Bind((CDate("WeatherDate")).ToShortDateString()) %>' so far, but got build errors saying the Bind was not well formed.

Anyone know what the correct syntax would be in this case?

Thanks


I would make a new topic for the problem with your date and give it a title about the date. Some people will know how to do this in vb but will not check this post because it is about calendar stuff :P


Good idea. Will do. Thanks for your help - you got me further than I was an hour ago!

Regards

Changing dynamically a user control within an UpdatePanel

I have a page that (using ajax), will dynamically route someone through a bunch of survey questions. Each survey page is written as a user control as each page needs to have a lot of flexibility, etc to visually add/edit HTML, blah, blah, but that's not the problem. I'm having a problem with loading the question too late in the page life cycle, so our respondent will see the following...

Introduction, Q1 (where they answer), Q1 again (as their answers aren't remembered), Q2 (Q1 answers were remembered this time), Q2 (again, cause Q2 answers weren't remembered first time again)... and so on, etc.

I know what the problem is, but I'm drawing a blank on how I can execute what I want properly. I've attached the code for my controlling page below. Thank you for any advice anyone can offer!!!

<%@dotnet.itags.org. Page Language="C#" MasterPageFile="~/survey.master" Title="Surveys" %>
<%@dotnet.itags.org. Import Namespace="SurveyWebControls" %><script runat="server">
const string SurveyStart ="SurveyStart";

SurveyPageBase currentSurveyPage;

protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme ="SurveyDefault";
}

protected void Page_Load(object sender, EventArgs e)
{
lblErrorMessage.Text ="";

if (txtCurrentSurveyPage.Value =="")
LoadSurveyPage(SurveyStart);
else LoadSurveyPage(txtCurrentSurveyPage.Value); }protected void btnNext_Click(object sender, ImageClickEventArgs e)
{
if (currentSurveyPage.Validated)
LoadSurveyPage(currentSurveyPage.NextPage);
else lblErrorMessage.Text = currentSurveyPage.ErrorMessage; }private void LoadSurveyPage(string QId)
{
Survey.Controls.Clear();
currentSurveyPage = (SurveyPageBase)LoadControl(QId +".ascx");
Survey.Controls.Add(currentSurveyPage);
txtCurrentSurveyPage.Value = currentSurveyPage.QId;
btnNext.Visible = currentSurveyPage.ShowNext;
}

</script
<asp:Content ID="SurveyBody" ContentPlaceHolderID="SurveyBody" Runat="Server">
<asp:UpdatePanel ID="SurveyUpdatePanel" runat="server">
<ContentTemplate>
<asp:HiddenField runat="server" ID="txtCurrentSurveyPage" />
<asp:Label runat="server" ID="lblErrorMessage" SkinID="ErrorMessage" />
<asp:PlaceHolder ID="Survey" runat="server" />
<br /><br />
<asp:ImageButton ID="btnNext" SkinID="NextButton" runat="server" OnClick="btnNext_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Try to use the template of asp:Wizard to load?user?controls?dynamically.?Try?to?take?a?look?at?the?following?materials?for?details.
http://msdn2.microsoft.com/en-us/library/fs0za4w6(VS.80).aspx
http://aspnet.4guysfromrolla.com/articles/061406-1.aspx
http://support.microsoft.com/kb/180405
http://weblogs.asp.net/sushilasb/archive/2004/03/31/104939.aspx
http://aspalliance.com/766_Working_with_the_Wizard_Control_Using_Visual_Studio_2005

Wish the above can help you.
I had thought of that, but it would still have to be dynamic. Sometimes there are literally hundreds of pages where someone might only go through 5 of them, based on how they answer previous questions.

Changing CSS or STYLE of TabContainer and TabPanes

Hi to all...

I have a question and i need answersSmile

I have a AJAX tabContainer witch add tabPanes dynamicly, but now i want to change the style or CSS of her, but i cant...

Can anyone help me!?

Hi Rikardo,

Here is a sample which indicates how to add css to the newly added Panel. If it is not you really want , please feel free to let me know with more explanations.

TabPanel myNewTab = new TabPanel();
myNewTab.ID = "TabPanel3";
myNewTab.HeaderText = "TabPanel3";
myNewTab.CssClass ="the tab css style";
Button myButton = new Button();
myButton.ID = "myButton";
myNewTab.Controls.Add(myButton);
this.TabContainer1.Tabs.Add(myNewTab);

I hope this help.

Best regards,

Jonathan


Jonathan Shen – MSFT:

Hi Rikardo,

Here is a sample which indicates how to add css to the newly added Panel. If it is not you really want , please feel free to let me know with more explanations.

TabPanel myNewTab = new TabPanel();
myNewTab.ID = "TabPanel3";
myNewTab.HeaderText = "TabPanel3";
myNewTab.CssClass ="the tab css style";
Button myButton = new Button();
myButton.ID = "myButton";
myNewTab.Controls.Add(myButton);
this.TabContainer1.Tabs.Add(myNewTab);

I hope this help.

Best regards,

Jonathan

In addition to the above

Just be careful when you are naming the css classes! There seems to be a bug in the tab panes extender, where strange things happen if you change the defaults css names.

follow this linkhttp://www.codeplex.com/AtlasControlToolkit/WorkItem/View.aspx?WorkItemId=11238 to Codeplex for comments and workarounds for this bug.

Good luck

changing button values on a tab

I have a AsP.net,VB.net app using tabs and I have two buttons at the bottom of the page that i want to change everytime the user goes to the next tab.

IE: btnBack and btnProceed, when you go to page two I want to change the image URL to be imageButtonBackToPage1 and imageButtonProceedToPage2 and so on, hope you get the idea.

Anyways, there are two ways for the user to go through the pages, 1 is using the tabs and 2 is using the buttons.

when the user uses the buttons i am able to change the imageurl easily but when the user uses the tabs nothing fires so I want to change the imageURl for the new page and saw that OnClientActiveTabChanged can find the active tab but I need a good example (of javascdript and HTML) of how to use this because I want to find out the active tabe and change the button images according to that.

Does anyone have good examples of how to do this? thanks.

Hi!

You could fire a post-back on Tab click using the following function, and setting the OnClientActiveTabChanged event toOnClientActiveTabChanged="ActiveTabChanged"

<script type="text/javascript">
function ActiveTabChanged(sender, e)
{
__doPostBack('<%= TabContainer1.ClientID%>', sender.get_activeTab().get_headerText());
}
</script>

Then, on code behind, use the TabContainer_ActiveTabChanged to change any values for the buttons.

Hope this helps,


thanks, what is the syntax for aclling ActiveTabChanged in the aspx page (what do you pass for sender and e?

Also, I am doing this with Ajax so I dont think the postback will work.


Hi,

Just scroll down the events drop-down list on VS 2005 and select ActiveIndexChanged on the TabContainer Control, then use the ActiveIndex or the ActivePanel properties to apply any code you need.
On server side you are not catching the javascript function, just using it as a trigger.

Why the post-back wouldn't work because AJAX? It's just firing an event which otherwise doesn't get fired by default. You can put your TabContainer inside an UpdatePanel and set the TabContainer_ActiveIndexChanged event as a trigger and you won't notice the difference. I'm using this approach and it works perfectly.


Thanks, this helps greatly, i am still learning Ajax. if you can post any sample code that would be great. thanks for your help, this saved me a lot of time.

Hi! You're welcome!

Just post your code and let us know where you are stuck, but basically is something like:

Protected Sub TabContainer1_ActiveTabChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabContainer1.ActiveTabChanged
If TabContainer1.ActiveTabIndex = 0 Then
Button1.ImageUrl = "YourPic"
ElseIf TabContainer1.ActiveTabIndex = 1 Then
Button2.ImageUrl = "YourPic"
End If
End Sub


thanks, almost there, one thing I noticed is that I had to set AutoPostBack=true for the TabContainer and now its capturing the event in the vb.net code. I thought I would be done with this task now but a funny thing is when I switch from tab to tab now its not changing the button images (i have code just like you wrote in your last post there) so I am really puzzled now, please let me know if any of you have any ideas. thanks.


Hi!

That's not a problem, just put your buttons inside UpdatePanels and call UpdatePanel.Update() from the TabContainer.ActiveIndexChanged event, or set the button's UpdatePanel triggers accordingly.


Thats it! thanks much, it works great now!


Hi! Well, I'm glad it helped!

Could you please mark the post answered to close the thread?

Cheers,

Changing Background Color Of Text box ?

Hello,

I need something as Follow..

I am having one Data Entry form. Here I have many controls (All type of controls like Textbox, Dropdownlis, Checkboxex esc...)

Now when user focus any text box then its Background color should change. Can we do it using ATLAS, xmlScript, Javascript...

one more problem is that I am having nearly 20 Text boxes on my page so which way I can get this functionality using less efforts...

Atlas is a really "heavy" way to do this. I'd just do it with Javascript and CSS.

<style type="text/css">

.normal

{

background-color:inherit;

}

.focus

{

background-color:yellow;

}

</style>

<script type="text/Javascript">

function changeTextbox(control){

var x = document.getElementByID(control);

if (x.classname == "normal"){

x.classname = "focus";

}

else {

x.classname = "normal")

}

}

</script>


Nice..

But the Parameter CONTROL in function... comes from where ?

Means from where we can pass it ?


You pass the control paramater when you call the function from the onFocus even of your textbox. It would be just as easy to capture the sender though, and get the calling object of the function, so it didnt need a paramater.
You don't need atlas or ajax at all, some javascript and dhtml will do:
foreach (Control ctrlin Form.Controls){if (ctrl.GetType() ==typeof(TextBox)) { ((TextBox)ctrl).Attributes.Add("onfocus","javascript:this.style.backgroundColor='red'"); ((TextBox)ctrl).Attributes.Add("onblur","javascript:this.style.backgroundColor='white'"); }}

Changing Background color of grid row when row checkbox selected

What option should I choose:

1) Write java script for this

2) Write server code and have grid in UpdatePanel

?

Not clear what the best guidline would be. I am already using update panel for that grid.

I guess the best solution should be if I have defined this background color in CSS.. I guess I could use java script to change the class name dynamicly and have that class defined in CSS. Not sure how to do it...


Here's some sample code I use in my custom ajaxed gridview control...

May or not work for you but should give you some idea..

 protectedvirtualvoid GridView_RowDataBound(Object s,GridViewRowEventArgs e)

{

if (e.Row.RowType ==DataControlRowType.DataRow )

{

//Note: Here is where we change the button submit so that

//our IPostBackHandler can properly handle AJAX requests.

int editID = (int)DataBinder.Eval(e.Row.DataItem,"id");

e.Row.Attributes.Add("onMouseOver","SetNewColor(this);");

e.Row.Attributes.Add("onMouseOut","SetOldColor(this);");

e.Row.Attributes.Add("onDblClick", Page.ClientScript.GetPostBackEventReference(this, e.Row.RowIndex.ToString()));

e.Row.Attributes.Add("onKeyDown","if( event.keyCode == 13 ) " + Page.ClientScript.GetPostBackEventReference(this,"KEYDOWN" +"$" + e.Row.DataItemIndex.ToString()));

Here is the code for adding it to the script manager on the prerender() phase

protected override void OnPreRender(EventArgs e) {string script = @." var _oldColor; function SetNewColor(source) { _oldColor = source.style.backgroundColor; source.style.backgroundColor = '#00ff00';} function SetOldColor(source) { source.style.backgroundColor = _oldColor; }"; ScriptManager.RegisterClientScriptBlock(this,typeof(Page),"ToggleScript", script,true);

Here is the aspx / ascx .Net code to use if you do not wanna do the PreRender event...

<script language="javascript" type="text/javascript"> var _oldColor; function SetNewColor(source) { _oldColor = source.style.backgroundColor; source.style.backgroundColor = '#00ff00';} function SetOldColor(source) { source.style.backgroundColor = _oldColor; } </script>

That should set you on the right direction....at least...


I have tried your aproach, I have created very similar code, but in my code I want to change ackground colour when the checkbox is chcked... It changes the color, but than it does not reverse it back to the old color... Any idea?

function highLight(CheckBoxObj){

var _oldColor;

if (CheckBoxObj.checked ==true) {

_oldColor = CheckBoxObj.parentElement.parentElement.style.backgroundColor;

CheckBoxObj.parentElement.parentElement.style.backgroundColor ='#D6DEEC';

//'#88AAFF';

}

else

{

CheckBoxObj.parentElement.parentElement.style.backgroundColor = _oldColor;

}


OK, I almost figured this out. My _OldColor variable needs to be global, outside of the function of course. OK, it seems to be working for one chcekbox at the time, but when multiple checkboxes are selected it doe not work. My guess would be I need to put the saved value to the array, but not sure how to do it...

var _oldColor;

function highLight(CheckBoxObj){

if (CheckBoxObj.checked ==true) {

_oldColor = CheckBoxObj.parentElement.parentElement.style.backgroundColor;

CheckBoxObj.parentElement.parentElement.style.backgroundColor ='#D6DEEC';

//'#88AAFF';

}

else

{

CheckBoxObj.parentElement.parentElement.style.backgroundColor = _oldColor;

}


In fact I suspect you may have the same problem happening in yourcode as you also do not put it (old color) into an array...

I was merely interested in just showing it highlighted for editing not necessarily for the checkboxes although that would be a nice feature to incorporate...

here some SAMPLE CODE to bite your teeth into - its out of the ajaxtoolkit... shows how to at least work with the arrays:

disableTab :function()

var i = 0;

var tagElements;

var tagElementsInPopUp =new Array();

this._saveTabIndexes.clear();

//Save all popup's tag in tagElementsInPopUp

for (var j = 0; j <this._tagWithTabIndex.length; j++) {

tagElements =this._foregroundElement.getElementsByTagName(this._tagWithTabIndex[j]);

for (var k = 0 ; k < tagElements.length; k++) {

tagElementsInPopUp[i] = tagElements[k];

i++;

}

}

Its from the ModalBehavior.js if you need to examine it a bit more...


Also some of the checkboxes can be initially checked as I keep track of those checked if user changes the pages... I used some code for this, I found on the web...

Thank you very much, the problem is how to get an index of the curren checkbox in the function (I am new to js):

function highLight(CheckBoxObj){

//var theBox=(spanChk.type=="checkbox")?spanChk:spanChk.children.item[0];

//xState=theBox.checked;

//elm=theBox.form.elements;

//for(i=0;i<elm.length;i++)

//if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)

//{

////elm[i].click();

//if(elm[i].checked!=xState)

//elm[i].click();

if (CheckBoxObj.checked ==true) {

_oldColor = CheckBoxObj.parentElement.parentElement.style.backgroundColor;

CheckBoxObj.parentElement.parentElement.style.backgroundColor ='#D6DEEC';

//'#88AAFF';

}

else

{

CheckBoxObj.parentElement.parentElement.style.backgroundColor = _oldColor;

}

This is my checkbox declaration (onclick works somehow, even not recognized by VS editor...):

<ItemTemplate>

<asp:CheckBoxid="chkActive"onclick="javascript:highLight(this);"runat="server"></asp:CheckBox>

</ItemTemplate>

changes to adding ScriptReference?

Greetings! I have a javascript file that does some rounded corners on my page called rounded.js. In Beta1 I declared it like this

<asp:ScriptManager ID="ScriptManager1" runat="server"> <Scripts> <asp:ScriptReference Path="~\rounded.js" /> </Scripts></asp:ScriptManager>

This is inside my Master Page. After the content place holders, at the end of the master page I have this.

<script type="text/javascript"> Rounded('header',6,6); Rounded('navigation',6,6); Rounded('content',10,10); Rounded('navigationright',6,6); Rounded('footer', 6, 6); </script>

It worked great with Beta1 but doesn't in Beta2. There are no rounded corners, and the javascript error reads:

Sys.ScriptLoadFailedException: The script 'rounded.js' could not be loaded or does not contain the Sys.Application.notifyScriptLoaded() callback.

Now, if I navigate with the back and forward buttons to pages inside my app, I still get the error, but the script does load somehow, because the rounded corners are there.

Please help!

Check out the release notes for the ASP.NET AJAX Extenstions (C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025\ReleaseNotes.txt)...

Under "4.3: Client Framework" you will see some notes about "* Script loading improvements". Relevant to your situation: "Component developers and page developers creating file-based script libraries that are registered with the ScriptManager control should include a JavaScript code snippet that indicates that the library has been downloaded by the client. Although this is not required in all browsers, Safari requires this to be able to dynamically load scripts."

Try adding this line to the very end of your 'rounded.js' file:

if(typeof(Sys) !='undefined') Sys.Application.notifyScriptLoaded();

Thanks,
Kyle


Is the CTP libraries also need this change?

I use this code to reference CTP libraries:

1<asp:ScriptManager ID="ScriptManager1" runat="server" >2<Scripts>3<asp:ScriptReference Path="~/PreviewDragDrop.js" />4<asp:ScriptReference Path="~/PreviewGlitz.js" />5<asp:ScriptReference Path="~/PreviewScript.js" />6</Scripts>7</asp:ScriptManager>
is it right? I copied these files to my site's root directory.
and I also got the "script could not loaded" exception while running...

hello.

well, i think the value added bits don't notify the sys.application object on completion of the load. so, you can add that line to the files or you can add them to the page through the <script> element.


hey all

im having the same problem now ive upgraded :-(

The solution was to add the following line:

if(typeof(Sys) !='undefined') Sys.Application.notifyScriptLoaded();

Im still getting the same error being thrown though :-( My JS file looks like this:

function

test()
{
alert("function called");
}
if(typeof(Sys) !='undefined') Sys.Application.notifyScriptLoaded();

and i call the script like this:

<

Scripts>
<asp:ScriptReferencePath="JScipt.js"/>
</Scripts>

What am i doing wrong??

Cheers Will


hello,

make sure IE is not caching the js file.


hey - thanks for the quick reply!

Yeh i just tried clearing out all the IE cache, but its still moaning :-(

What else could i be doing wrong?


hello.try debugging the page and make sure that the call to notifyscriptloaded is being made.

ok im getting somewhere!

i tried changing the script path on my test project to an absolute path

before: Path="JScript.js"

after: Path="http://localhost:2303/AjaxControlToolkitWebSite1/JScript2.js"

all works fine! this is not summet i want to do, so why is not looking in the wrong place?

Cheers for ya help dude

Will


hello.

i've been having some problems with the internal server, ie, i'm having several issues with the caching of files when i use the internal server.


I am having the exact same problem with the internal server caching files...did you figure out a good work around?

Thanks, Greg Benoit


hello.

wll, not really. i've started using IIS :)


What are the steps for converting an existing file based project to using IIS?? I tried and almost got it working, but when I went to login using my login control and the aspnetdb the login control reported back that my login credentials were incorrect??

Thanks, Greg