Thursday, April 16, 2009

AjaxControlToolkit’ TabContainer control’ Javascript functions.

In my previous two blogs we saw some javascript tricks to work with ASP.NET AJAX controls. The links to my previous blogs are

In this blog we will start with a common requirement for the tab container control i.e. setting focus to a tab using javascript and later at the end of this blog we will also see some important javascript functions available with ASP.NET AJAX Tab Container control.

One of the coolest controls in the ASP.NET AJAX is the TabContainer. Recently I had the requirement to show controls in tabs and also if there was any validation error in any of the tab I need to set focus on that tab as well. So if you also have the same requirement like you wanted to set focus to a particular tab of ASP.NET Ajax TabContainer control using javascript then read on. Below is the html code for the page having a tab container and some other asp.net controls like the validation control, validator callout etc.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AJAXControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        <AJAXControls:TabContainer runat="server" ID="tabContainer">
            <AJAXControls:TabPanel ID="firstTab" HeaderText="First Tab" runat="server">
                <ContentTemplate>
                    <asp:Label ID="Label1" runat="server">You are in the First tab. <br /> Press the submit button to see the validation result.</asp:Label>
                </ContentTemplate>
            </AJAXControls:TabPanel>
            <AJAXControls:TabPanel ID="secondTab" HeaderText="Second Tab" runat="server">
                <ContentTemplate>
                    <label id="Label2" runat="server">Please select a value from the drop down: </label>
                    <!--ASP.NET Drop down control-->
                    <asp:DropDownList ID="status" runat="server" >
                        <asp:ListItem Selected="True" Text="Select" Value="0" />
                        <asp:ListItem Text="One" />
                        <asp:ListItem Text="Two" />
                        <asp:ListItem Text="Three" />
                    </asp:DropDownList>
                    <!--ASP.NET Required Field Validator to validate the drop down.-->
                    <asp:RequiredFieldValidator ID="statusValidator" runat="server" ErrorMessage="Please choose a value other than 'Select'" ControlToValidate="status" InitialValue="0" Visible="true" Display="None">
                    </asp:RequiredFieldValidator>
                    <AJAXControls:ValidatorCalloutExtender ID="statusValidator_ValidatorCalloutExtender"
                        runat="server" TargetControlID="statusValidator">                     </AJAXControls:ValidatorCalloutExtender>                   
                </ContentTemplate>
            </AJAXControls:TabPanel>
        </AJAXControls:TabContainer>
        <br />
        <asp:Button ID="submit" Text="Submit" OnClientClick="javascript:return ValidatePage();"
            runat="server" />
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    </div>
    </form>
</body>
</html>

So in the above html code you can see we have an AjaxControlToolkit TabContainer control with two TabPanels having id as “firstTab” and “secondTab”. The first tab has a label control and the second tab has a dropdown control with a validation control attached to it and a ValidatorCalloutExtender control attached to the validation control. Also we have a submit button with “OnClientClick” event calling a javscript function called “ValidatePage”. Now the problem is whenever the submit button is pressed and if there is a validation error in the second tab the user is not informed of the same, reason being he is in the first tab and error has happened in the second tab. When the user manually clicks on the second tab he is able to see the error and if he doesn’t click the second tab the user is oblivious of the error. The solution to the problem is to set focus on the second tab whenever there is a validation error in the second tab. The javascript solution for the same is pasted below.

<script language="javascript" type="text/javascript">
function ValidatePage()
{
    // Getting the validation control using the new $get function.
    var valCntl = $get('<%=statusValidator.ClientID%>');
    if (valCntl != undefined && valCntl != null)
    {
        /*ValidatorValidate function executes the validation logic associated with the validation control. */
        ValidatorValidate(valCntl); 
    /*isvalid property is set to a boolean value by the ValidatorValidate based on whether the validation logic associated with the validation control was successful or not. */
        if (!valCntl.isvalid)
        {
        /*User defined method to hide the validator callout control.
            hideValidatorCallout(); */
        /*Retrieving the tab container control using new $get javascript function. */
            var tabContainer = $get('<%=tabContainer.ClientID%>');
            if (tabContainer != undefined && tabContainer != null)
            {
                tabContainer = tabContainer.control;
                tabContainer.set_activeTabIndex(1);
                showValidatorCallout();
            }
            return false;
        }
        return true;
    }
}

function hideValidatorCallout()
{    
    /*Below code hides the active AjaxControlToolkit ValidatorCalloutExtender control. */
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.hide();
}

function showValidatorCallout()
{
    /*Gets the AjaxControlToolkit ValidatorCalloutExtender control using the $find method. */
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout = $find('<% =statusValidator_ValidatorCalloutExtender.ClientID %>');
    //Below code unhides the AjaxControlToolkit ValidatorCalloutExtender control.
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.show(true);
}
</script>

If you see in the above code we are calling ValidatePage javascript method on the button’ OnClientClick event. Inside the function we are making a call to the ValidatorValidate method with the validation control as the argument. Once that is done I am checking whether the validation logic associated with validation control has executed successfully or not by checking the isvalid property of the validation control. If the validation is not successful I am getting the tab container control using the “$get” javascript method. Once the tab container is retrieved the following two lines sets the focus to the desired tab.

tabContainer = tabContainer.control; 
tabContainer.set_activeTabIndex(1);

Once you retrieve the tab container object using the “control” property one can use “set_activeTabIndex” to set the focus to the required tab. The “set_activeTabIndex” method takes an integer (tab index) value as the argument. Using the “set_activeTabIndex” javascript method one can set focus to the required tab.

I have used a new javascript function called “$get” to retrieve an element. In my previous blog I have used “$find”, we will see the difference between these two in my next blog but for the time being just understand that “$get” is the short cut for “document.getElementById” javascript method.

Some other useful tab container control’ javascript functions

Below I have listed some of the important javscript functions which may be of use for developers like us. These methods can be used only after one has retrieved the ASP.NET AJAX TabContainer control using the following code “TABCONTAINER_CONTROL.control” as shown in the above codes.

Method Explanation
get_activeTab()

returns the current active tab javascript object i.e. the tab which is in focus. This javascript function gets the active tab object.

get_activeTabIndex()

gets the active tab index. The function returns an integer value of the active tab.

get_id() gets the id of the tab container control.
get_tabs() gets an array of all the tabs in a tab container control. The function returns a javascript array containing all the tabs in the tab container control.
get_visible()

returns a boolean value indicating whether the tab container is visible or not.

getFirstTab() gets the first tab in the tab container control. The function returns a tab having tab index 0.
getLastTab() gets the last tab in the tab container control. The function returns a tab object having tab index = (tab count) –1.
getNearestTab()

gets the nearest tab. If the current tab index is 0 then the method will return second tab i.e. the tab having tab index as 1 and if the tab index is greater than 0 the function will return the previous tab i.e. the tab having index = [Current Tab Index] – 1.

getNextTab()

gets the next tab in the tab container control i.e. if the current active tab is the last tab then the function will return the first tab as the next tab else it will return the next tab ([Current Tab Index] + 1)

getPreviousTab()

gets the previous tab in the tab container control i.e. if the current tab index is 0 then the function returns the last tab else it returns the previous tab ([Current Tab Index] - 1)

set_activeTab(tabControl)

sets the active tab. The function takes a tab object as its argument and sets the tab as the active tab.

set_activeTabIndex(integer)

functions takes an integer value starting from 0 to tab collection length – 1 as an argument and sets the tab’ index matching the integer value as the active tab.

set_id()

sets the id for the current tab container control.

set_visible(Boolean)

function takes a Boolean value and based on the value, hides or shows the tab container. The function/property makes the whole tab container control visible or invisible. To make individual tabs visible or invisible you need to work with the tabs property as shown in the below table.

Individual Tab object’ javascript functions

The above functions are related to the tab container control. There may situation where one might want to work with individual tab objects. To work with individual tabs one has to retrieve the individual tab by making us of any of the above tab retrieval functions from the table and then one can work with the individual tab. Sample e.g to retrieve individual tab is given below.

tabContainer = tabContainer.control;
//Retrieving the tab using the get_activeTab method/property
var tab = tabContainer.get_activeTab();
var headerText = tab.get_headerText();
alert(headerText);
//Another way of retrieving the tab using the get_previousTab method/property
tab = tabContainer.getPreviousTab();
alert(tab.get_tabIndex());

Once you have retrieved the individual tab using any of the above methods you can make use of some of the useful methods listed in the table below to work with the tab object. The methods listed in the below table are not the complete list but they are some of the methods which I feel may be useful for developers.

Methods Explanation
addCssClass(className) sets the CSS class. The function takes the CSS class name as the argument. You can make use of this javascript function to change the CSS class of a tab at runtime through javascript.
get_enabled()

gets a Boolean value indicating whether the tab is enabled or not (disabled). The function returns true or false.

get_headerText()

gets the header text of the tab. The function returns string containing the header text.

get_id() gets the id of the tab.
get_tabIndex() gets the tab index of the tab object. The function returns an integer.
get_visible() gets whether the tab is visible or not. The function returns a boolean value.
removeCssClass(className)

removes the CSS class based on the class name passed in the argument.

set_enabled(Boolean)

enables or disables the tab object based on the boolean value passed.

set_headerText(string)

function sets the header text for tab. Functions takes a string as an argument and sets the string as the header text.

set_id() sets the id for the tab.
set_visible(Boolean)

sets the visibility of the tab based on the boolean argument passed. The boolean value makes the tab visible or invisible.

In my next blog we will see the difference between $find and $get. Till then try to know more.

Sandeep.

125 comments:

  1. Geat job!! Thanks

    ReplyDelete
  2. Thanks for the positive comments.

    ReplyDelete
  3. This is great, thanks. Do you think you can help me out with something? What I need to do is set focus to the first nonhidden texbox element within each tab. How can I loop through all the items in the active tab and focus on the first one?

    ReplyDelete
  4. This is great, thanks. Do you think you can help me out with something? What I need to do is set focus to the first nonhidden texbox element within each tab. How can I loop through all the items in the active tab and focus on the first one?

    ReplyDelete
  5. Hi Belle,
    Yes, I can help you on this. Due to some reason blogspot is not allowing me to paste the javascript code. I can give you the idea on how to do this and if you want the whole code you can give me your mail id. I will mail you the same.
    Here is the idea on how to do it.

    //Getting tab control using the $get method by passing the id of tab control
    var tabContainer = $get('tabContainer');
    if (tabContainer != undefined && tabContainer != null)
    {
    tabContainer = tabContainer.control;
    //Retrieving the tab using the get_activeTab method/property
    var tab = tabContainer.get_activeTab();
    //Getting all the controls inside the tab.
    var controls = tab._element.all;
    // Loop through the control using any of the javascript looping technique.
    //Inside the loop check the following condition.
    if (controls[i].tagName == "INPUT" && controls[i].style.visibility != "hidden")
    {
    controls[i].focus;
    break;
    }
    }

    Thanks
    Sandeep

    ReplyDelete
  6. good job !
    Could u help me - i need to get tab's header as element to set another css style for selected tab (ajax's styles as ".ajax__tab_tab", "ajax__tab_outer .ajax__tab_inner" not helps due to specific design)?

    ReplyDelete
  7. Hi Anonymous,
    There are two ways to do this. The code is pasted below. As the comment section doesn't allow to paste codes I am giving you Idea. If you could send me your mail id I will mail the code.
    1. First Get tab control using any of the above methods.
    2. Second Get the control using the control property of the tab container
    tabContainer = tabContainer.control
    3. Get the active tab using the get_activeTab method
    var tab = tabContainer.get_activeTab()
    4. Use the header property of the tab and set the className property to assign the new css class
    tab._header.className = "style sheet class name"
    5. Second of doing is after getting the active tag call the get_headerTab method and get the header object.
    header = tab.get_headerTab()
    6. Set the className property.
    header.className = "style sheet class name"

    ReplyDelete
  8. Hi Sandeep,
    The article is excellent.Thanks for the same. I am facing a problem and I hope you can help me out.
    I have a ModalPopupExtender popup window in ASP.Net, with 3 tabs. I am using the AJAXControls:TabContainer control.
    I use this popup in 2 conditions.
    Firstly to edit client data and secondly to insert a new client's data. On change of the tabs I call the ActiveTabChanged event. In this event, I have javascript code that validates controls on the current tab, and if all validations are fine, moves to the tab that has been selected, else stays on the current tab.
    Also, I am using form validators (Req. Field Validator etc with ValidatorCalloutExtender) for controls on each tab.
    So if I have not entered a value for Client Name textbox in the first tab and I try to go to the next tab, it popups the ValidatorCalloutExtender and prevents me from going to the next tab (due to js code in ActiveTabChanged event).
    This works fine when I am editting a client and I delete the existing client name from the Client Name textbox, and navigate to the next tab.
    However, when I am creating a new client, the Client Name text box is empty in the first tab and without clicking on any control in this tab, I click on the second tab. It prevents me from navigating to the second tab, due to the ActiveTabChanged event. However the ValidatorCalloutExtender does not popup unless I click in the client name textbox.
    Hence the user would be left wondering why he is unable to navigate to the second ahd third tab, since no error popup is being displayed.
    Kindly let me know if you have any inputs on this. My entire problem is focused on making the ValidatorCalloutExtender visible, when I navigate between tabs.

    Thanks in advance,
    Sulaksha

    ReplyDelete
  9. Hi Sulaksha,
    It will be great if you could send me the code. Seeing the code I will be able to help you more. You may not be able to post the code here so you can send mail to sndppr@gmail.com.

    ReplyDelete
  10. Hi Sandeep,

    iam using ajax tabcontainer, iam clicking on tabs its displaying different forms, i want write javascript validation for one of my multiline textbox in the form, but it is showing this error.

    The Controls collection cannot be modified because the control contains code blocks (i.e.

    but this code is working for normal forms (not using tab container). What is the problem. How to use the javascript code for my forms(that forms in tabcontainer).


    Thanks in Advance.

    Regards
    Suma.

    ReplyDelete
  11. Hi Suma,
    I am unable to understand what is the problem which you are facing. It will great if you could send across the code.

    ReplyDelete
  12. This was kick ass man! Thank you so much for exposing the the tab control's methods!!

    Can you tell me how you found those methods so that I might be able to expose all the ajax.net toolkit controls methods??

    ReplyDelete
  13. Thanks, When I started working on these controls I came to know that there are javascript methods related to these controls and then made use of the watch window of Visual studio to explore the methods. Sadly there are not much documented about these methods, so I thought I will spread the news.

    ReplyDelete
  14. Hi Sandeep,
    I really appreciate the way you presented the content and made our life easy. :)I am facing one typical problem with Ajax TabContainer,I have to hide some tab panels from my code behind depending on a condition but after doing that i see that the tabcontainer is behaving abruptly i.e. it is showing me the wrong headertext and index of the active tab.What i felt is the tabcontainer is maintaining the indexes of the tab statically that is once the tabs are hidden it is not changing the index.i.e. for example i have 3 tabs Tab1,Tab2 and Tab3 in my page, now from code behind i have hidden Tab2 so in UI only Tab1 and Tab3 appears in UI but when i want to access the header text or index of active tab on click of Tab3 it is showing me the information of Tab2.It would be of great help if you can tell me how can i get rid of this problem(and i have to do this from server side code only)?One more thing i want you to tell is what is the easiest and best way of doing lazy loading for the tabs.

    Regards,
    Shubh

    ReplyDelete
  15. Hi Shubh,
    Without seeing the code I may not be able to help much. Please send the code to sndppr@gmail.com. Also the best way to lazy load is putting the tab container in an UpdatePanel.

    ReplyDelete
  16. Hi Sandeep,
    I have sent u the detail.Pls Chk and let me know.
    I wanted the steps for lazy loading in much elaborately,a step-wise explanation would be much helpful.

    Regards,
    Shubh

    ReplyDelete
  17. Hi Sandeep,
    I have the same issue as Shubh has. Please give the solution from server side.

    Regards,
    Satya

    ReplyDelete
  18. Hi Satya,
    It will great if you could send the code along with you problem to me. My mail id is sndppr@gmail.com

    ReplyDelete
  19. Hi sandeep,
    I'm having a problem with asp.net ajax tab container.i succeeded in disabling the tabs and after clicking a button in my first tabpanel, i'm showing second tabpanel and respectievely third and fourth tabs..
    till yesterday my logic worked fine.. But today it is behaving strangely, my button click is not working fine.
    i'm using 2 dropdown lists on tabpanel1, when user selects first dropdown list then i'm enabling secnond dropdown list. can you please help me out??
    Many Thanks,
    I'll email you my code if you can check it..
    awaiting your response

    ReplyDelete
  20. Hi Pavan,
    Please send me the code so that I can have better understanding of what went wrong.

    ReplyDelete
  21. Hi Sandeep,

    Your blog was very informative.

    Could you please help me with the following problem?

    I have a custom panel that contains server controls. AutoPost Back is enabled on few of these controls. This panel is added to 2 tabs.

    The event handler is invoked for the controls on the first tab. But this is not the case with the second tab.

    Can you give me clue...

    Thank you...

    ReplyDelete
  22. Hi,
    It will great if you could send me the code on how you have implemented the custom panel and stuffs like that. Seeing the code will help to narrow down the problem.

    Thanks

    ReplyDelete
  23. break don't work under if/else statements.
    Do we have a different mechanism. I don't want to use switch.

    Thanks for the help.

    ReplyDelete
  24. Hi,
    Break wont work in if/else statement as it is meant to break a loop or a switch statement. From within a if/else statement you want to exit the function just make use of a return keyword. Return keyword come out of the function.

    ReplyDelete
  25. hi sandeep

    i'm sabari eagerly interested in .net.i had used tabcontiner in my application.But when executing one time the page is blank and while executing some of exceptions has thrown that is system.web.ui.scriptbaserefernce and publickey token error.How to avoid and execute my application.To view a page in a tab i had used simple iframe concept.
    Expecting your favourable reply sir

    ReplyDelete
  26. Hi Sabari/Hari,
    It will be great if you could send some code samples of what you are doing. The error can be rectified by properly adding the ASP.NET AJAX framework, think so.
    Using IFrame is not the best of way doing things. Instead I would suggest you to make use of user controls. Any page can be easily converted to an user control.

    ReplyDelete
  27. hi am Neetika
    I have problem in if-else condition ..its not working..it will be great if u help me..
    here is my code


    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Data.SqlClient;

    public partial class Management_Staff_Salary_Details : System.Web.UI.Page
    {


    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BtnSubmit_Click(object sender, EventArgs e)
    {
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString);

    //string sql = "Select * from ManstaSalary";
    //SqlCommand cmd = new SqlCommand(sql, con);

    if (DDlDepartment.SelectedValue !=null&& DDLStaffID.SelectedValue !=null)
    {

    con.Open();
    string str1 = DDlDepartment.SelectedValue;
    string str2 = DDLStaffID.SelectedValue;
    //string str3 = DDlStafftype.SelectedValue;
    //string sql1 = "Select * from ManstaSalary where Department='" + str1 + "'and StaffID='" + str2+ "'";


    SqlDataAdapter ad = new SqlDataAdapter("Select * from ManstaSalary where Department='" + str1 + "' AND StaffID = '" + str2 + "'", con);
    DataSet ds = new DataSet();
    ad.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    con.Close();
    }
    else
    if (DDlDepartment.SelectedValue != null)
    {

    con.Open();
    string str = DDlDepartment.SelectedValue;
    //string sql = "Select * from ManstaSalary where Department= '" + str+"'" ;

    SqlDataAdapter ad = new SqlDataAdapter("Select * from ManstaSalary where Department= '" + str + "'", con);
    DataSet ds = new DataSet();
    ad.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    con.Close();

    }

    }
    }

    ReplyDelete
  28. Hi Neetika,
    You have said that you have problem, but you have not elaborated on what exactly the problem is. Could you let me know what exactly the problem is?

    ReplyDelete
  29. Hi Sandeep,

    Just a little question, can I set a tab disable (with set_enabled(false)) and keep it visible ? Now, when I disable the tab, they dissapear.

    Thanks

    ReplyDelete
  30. hi,
    I'm new to Ajax.I want to add tabs to my tabcontainer while pageloading,taking the headertext from database.Please help me as soon as possible.

    ReplyDelete
  31. Hi Doum,
    Sorry for the late reply. I didn't find anything of the sort you were saying. I tried disabling the tabs and they wr very much visible. The code used are pasted below.
    var tabControl = $find('<%=TabContainer1.ClientID %>')
    var tabContainer = tabControl.get_tabs()[0].set_enabled(false);
    //Another way of disabling the tab container
    var tabControl = $get('<%=TabContainer1.ClientID %>')
    var tabContainer = tabControl.control
    tabContainer.get_tabs()[0].set_enabled(false);

    ReplyDelete
  32. Hi,
    Regarding adding tab to the tab container on page load, its quite easy. Sample code is pasted below.
    var tp = new AjaxControlToolkit.TabPanel();
    tp.HeaderText = "Something from the database";
    this.TabContainer1.Tabs.Add(tp);

    ReplyDelete
  33. Hi sir,
    Thanks for the reply.

    ReplyDelete
  34. Hi Sandeep

    I want to hide the tab panel depend upon the codition

    I used this below code to hide the tab panel

    "tabContainer1.Tabs(1).Enabled = False"

    which worked(With the above I could be able to hide that tab panel) well in the .Net Framework2.0 environment.Recently we moved to 4.0 Framework now the problem started.In 4.0 not able to hide the panel,(visible property also dont work for me).

    I used your suggested code, that also didn't help me:
    var tabControl = $get('<%=TabContainer1.ClientID %>')
    var tabContainer = tabControl.control
    tabContainer.get_tabs()[0].set_visible(false);


    It would be great if you can look into this issue, I need a quick reply,Please.

    Thanks in Advance

    Anil Siddi

    ReplyDelete
  35. Hi Anil,
    I am using the "3.5.40412.0" version of AjaxControlToolkit. The above codes are working perfectly fine for me. Can you send me across the code you are using?

    ReplyDelete
  36. Hi..

    Thanks for quick reply.

    I now using the "4.1.40412.2" version of AjaxControlToolkit.Before we used "1.0.XXX.." It worked fine then with the following code:

    tabContainer1.Tabs(1).Enabled = False--->To hide the container

    Is that the issue of dll version.If yes please let me know what should I do to solve the problem.

    ReplyDelete
  37. Hello Sandeep

    I used the below code to hide the panel:

    tabContainer1.Tabs(1).Enabled = False--->To hide the tab panel

    ReplyDelete
  38. Hi..

    I solved this problem by using the following:

    $find('" & tabc.ClientID & "').get_tabs()[12]._hide();

    _hide() works for me

    Thanks for your support.

    ReplyDelete
  39. Error in Ajax HTML editor control. Its not taking blank line. Can ne one please help me in this

    ReplyDelete
  40. Hi Pallavi,
    Can you please elaborate on the error or if you could send the code it will be of great help to find a solution to your prob.

    ReplyDelete
  41. Hi Sandeep,

    Thanks for great info! I'm a newbie... How could I open to a specific tab using a URL parameter? I would like to use the 'HeaderText' property as the parameter (and not the 'ActiveTabIndex' because it changes if the tabs are reorganized).

    ReplyDelete
  42. Hi,
    For your requirement you need to loop through all the tabs and check the "HeaderText" property and then assign the tab as the "ActiveTab". The code is pasted below.
    for (var i = 0; i < this.TabContainer1.Tabs.Count; i++)
    {
    if (this.TabContainer1.Tabs[i].HeaderText == Request.QueryString["HeaderParameterName"])
    this.TabContainer1.ActiveTab = this.TabContainer1.Tabs[i];
    }

    ReplyDelete
  43. Hi Sandeep,
    Thanks for the post above, I'm looking for answer but not finding anywhere.
    I've a tabContainer in my form with 4 tabs.
    I want the user nevigate between the tab only with button's and can't use the header.

    Guy

    ReplyDelete
  44. help!!! IE return a null object when ex'ing this code..

    function SacochangeTab(tabIndex){
    var tabBehavior = $get('<%=tabcontainerCity.ClientID%>');

    if ((tabBehavior != null) && (tabBehavior != undefined)){
    alert(tabBehavior);
    tabBehavior.control.set_activeTab(tabBehavior.control.get_tabs()[tabIndex]);
    //tabBehavior.set_activeTabIndex(tabIndex);
    autoRefresh = null;
    changed = 1;
    }

    }

    ReplyDelete
  45. Hi Guy,
    One option which I can think of is to override the default css and change the cursor symbol whereby the user will not see the hand symbol. And the next would be to handle the "OnClientActiveTabChanged" in javascript. You can reassign the old tab in the event. Though I have not tried this I think it can help. Please let me know the outcome.

    ReplyDelete
  46. Hi Anonymous,
    About IE returning I need to take a look at the bigger picture i.e. the whole aspx page from where this function is getting called. It will be great if you can send me across the whole aspx html code.

    ReplyDelete
  47. Hi Sandeep,

    I wonder whether you can help me with one of my issue. I have an AJAX tab in a page and on button click I need to call a javascript function which has an alert function in it. I used the following code to do that
    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "testPostback();", true);

    but the issue is the tab get disappear while javascript function displays the text. Is there a way to prevent tab from disappearing.

    Thanks in Advance.

    ReplyDelete
  48. Hi,
    To help with disappearance issue I would like to look at the whole code. Please send across the code to sndppr@gmail.com.

    ReplyDelete
  49. Hi,

    From the code you have sent it was found that you are using "RegisterClientScriptBlock" method of "ScriptManager" class to call a javascript method which is not the intended functionality of "RegisterClientScriptBlock" method. It is intended to register a block of javascript (script with function and body) code. It can also be used the way you have done but that will not solve your problem.

    To call a javascript function on the click of a button you can make use of "OnClientClick" property or "Add" method of the "Attributes" property of the control to register you click event. Sample code is pasted below.

    Making use of "OnClientClick" event.


    Making use of "Attributes.Add"
    if (!IsPostBack) this.Button1.Attributes.Add("onclick", "testPostback();");

    The reason why your tab control disappears is that when the page postbacks the click event gets fired and in the click event you have written code to register a script which calls "testPostback" method before the page is loaded. This function call prevents the page from completely getting loaded and that is the reason why you are not able to see the tab control. Once you have clicked "Ok" of the javascript' "alert" message box you see the tab control once again.

    ReplyDelete
  50. Hi Sandeep,

    Thank you very much for your help.
    Unfortunately "OnClientClick" will not help me. If you look at my code, I have to perform a server operation first and then display the result of the operation using Java Script function. I can do that successfully on a normal aspx page with the help of "RegisterClientScriptBlock" block. But when I have an AJAX tab on it, i have the problem explained earlier.
    I intend to pass some parameters to my "testPostback()" function so that I can use the same function to alert the status of server side operation.
    If "RegisterClientScriptBlock" can't do it, is there any other function that can meet this requirement.
    Once again I Appreciate your time and help.

    Many Thanks
    Linse


    Hi Jose,

    Thanks for the clarification.
    The other way is to use "RegisterStartupScript" which registers the script at the end of the page. But this also will hide the tab control. The other option I can think of is using a time delay by making use of "setTimeout" javascript function. Sample code is pasted below.
    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "", "setTimeout(\"testPostback()\", 1000);", true);

    Please let me know whether this solved your prob?
    Regards,
    Sandeep


    Hi Sandeep,

    Thanks for the quick feedback. "setTimeout" worked perfectly. I believe the timeout function will delay only the javascript function (correct me if I am wrong.)
    To be honest I am not a great fan of this method as the interval set may not be the optimal one for actual users on a varied internet speed.
    Thank you for your help.
    Yes, this is not a great solution but for your requirement this is the only one I can think of. If the tabs were not getting displayed then we could have done away with it.

    ReplyDelete
  51. Hi Sandeep,
    Is it possible to navigate the ajax tab container using tab key.

    For eg: From the 1st tab, if i press tab key, it should go to 2nd tab.

    ReplyDelete
  52. Hi,
    Yes, it is very much possible to navigate from one tab to another using tab key. For this you need to register "keydown/onkeydown" events for the header of the tab. Sample code is pasted below.
    var tabC = $find('<%=TabPanel1.ClientID %>');
    if (tabC._header.addEventListner)
    tabC._header.addEventListner("keydown", this.keyHandler, false);
    if (tabC._header.attachEvent)//Checking for IE
    tabC._header.attachEvent("onkeydown", this.keyHandler);

    function keyHandler(e) {
    if (e.keyCode == 9) {
    this.value += " ";
    //preventDefault works except in IE
    if (e.preventDefault)
    e.preventDefault();
    var tabContainer = $find('<%=TabContainer1.ClientID %>');
    tabContainer.set_activeTabIndex(1);
    return false;//IE hack.
    }
    }

    The above code works only when you press tab when the focus is on the tab header. If you want to implement in controls inside a tab then you need to attach the keydown event for the controls as well.

    ReplyDelete
  53. Hi Sandeep,

    Very useful article. I just wanted to know how to get all the controls in a tab in tabcontainer.I just want the code.

    ReplyDelete
  54. Hi Ashish,
    You can use "get_element" method of individual tabs or you can use "_element" property to retrieve the controls inside a tab. Sample code is pasted below.

    var tabControl = $find('<%=TabContainer1.ClientID %>');
    //Will give the controls inside a tab.
    var controls = tabControl._tabs[0]._element.children;
    //Or one can use something like this
    var controls = tabControl._tabs[0].get_element().children;

    ReplyDelete
  55. This comment has been removed by the author.

    ReplyDelete
  56. Hi Sandeep,
    I am using a TabContainer which has two TabPanels, TabPanel1 and TabPanel2.

    On PageLoad TabPanel1 is active.
    And each TabPanel has two textboxes.

    When i try to navigate the texboxes by using TAB key it allows me to navigate between texboxes in one TabPanel and it doesn't allow me to navigate to other TabPanel by pressing Tab key.

    For navigation order i am specifying the TabIndex property for textboxes controls and TabPanels.

    Any help is more than welcome

    ReplyDelete
  57. Hi Kulbir,
    Pressing the tab key will not automatically show the next tab even if you set the tab index. You need to use javascript to do this. Register "onkeydown" event for the last textbox in your tab and in the "onkeydown" event function call write the following code.

    Add the following javascript to change tab.
    function changeTab(e) {
    if (e.keyCode == 9) {
    this.value += " ";
    //preventDefault works except in IE
    if (e.preventDefault)
    e.preventDefault();
    var tabContainer = $find('<%=TabContainer1.ClientID %>');
    tabContainer.set_activeTabIndex(1);
    return false;//IE hack.
    }
    }

    Hope this helps.

    ReplyDelete
  58. Hi am very new to asp.net and i have tried the code, am geting the tabcontainer on the design window but while running am seeing only a button . plz plz help as soon as possible.

    ReplyDelete
  59. Hi Dimple,
    Again from what you have explained its very hard to know what is the actual reason why you are not able 2 see tab container. It will be helpful if you could paste your code or send it to me @ sndppr@gmail.com

    ReplyDelete
  60. This comment has been removed by the author.

    ReplyDelete
  61. Hi i am ramesh .......
    i my application i use usercontrol in that i use one tab container that have 3 tab panels i want to set some events for each tab panel for tab load through script please help me how to call the events in tab panel load......

    ReplyDelete
  62. Hi Ramesh,
    I doubt if there is any load event associated with the tab panels. There is _oncomplete method for the TabContainer control. How useful it will be I am doubtful? Then there is the initialize method for individual tab panels which you may like to use. One more thing which you can try is set the events or other logic at the click of the tab panel header event. If you read some the previous comments you will find the code to register tab panel header clicked event.

    ReplyDelete
  63. Hi,

    I have a TabControl with 5 TabPanels. On page load, I just need to show the first tab. Based on menu item click, I need to show the remaining tabs. This works on server side by setting tab index like here. TabContainer1.Tabs[1].Visible = false;

    The issue I have is then the controls inside the tabpanels or even tabpanels are not accessible in javascript. So I tried the following code.

    var tabContainer1 = $get("<%=TabContainer1.ClientID %>");
    var tabContainer = tabContainer1.control;
    var tab = tabContainer.get_activeTab();
    tab.set_visible(false);

    Again this doesn't work. Tabs are visible. Any help would be appreciated.

    Thanks for your time.
    Linse Jose

    ReplyDelete
  64. Hi Sandeep,

    This post of yours served my purpose to some extent. But I need more help with the tabcontainer.
    I have 3 different tabs within the tabcontainer and in each tab I have a submit button.
    What I want to do is when the user is in the first tab I want other tabs to be disabled and when the user clicks on the submit button in this current tab the user has to be navigated to the next tab automatically.
    Is this possible. Please help me.

    ReplyDelete
  65. Hi sandeep,
    please use the below url and click on Eviroland V3.0 to
    download it. after downloading please install it in
    your system. It is developed for chemistry laboratory
    practise. i want to develop it in c# using asp.net.
    Any idea

    ReplyDelete
  66. i missed to mention the link in above post.
    use this
    http://www.edusolns.com/enviroland/download.shtml

    ReplyDelete
  67. Hi sandeep I m Anubhav,
    Could u plz tell me how to retrieve the value of a textbox which is within a tabcontainer....

    here is the structure of my tabcontainer :

    -tabcontainer
    -tabpanel
    -headertemplate

    -headertemplate
    -contenttemplate
    -.....textbox......-//retrieve value
    -contenttemplate
    -tabpanel

    -tabpanel
    -headertemplate

    -headertemplate
    -contenttemplate
    -.....textbox......-//retrieve value
    -contenttemplate
    -tabpanel
    -tabcontainer

    ReplyDelete
  68. Hi Indumathi,
    Sorry for late reply. Could you please elaborate what is your requirement or what is holding you back from converting the said application to ASP.NET. I am unable to install the app in my laptop due to company policies.

    ReplyDelete
  69. Hi Anubhavtech,
    You can use document.getElementById('YourTextBoxID').value to retrieve the textbox' value.

    ReplyDelete
  70. Hi sandeeep

    I wanna concentrate string and tab it is possible

    Its very urgent

    ReplyDelete
  71. Hi sandeeep


    I hope u doing well

    In ajax tabcontainer(.net framework 2.0) i need to disable and enable my tab(grey out). but now its make visible false

    Its very urgent

    ReplyDelete
  72. Hi,
    I didn't get your question of concatenate string and tab. If you want to set a header text then you can use "set_headerText('HEADER_TEXT')" method of a tab.

    ReplyDelete
  73. To disable and enable an individual tab you can use "set_enabled(BOOLEAN)" method of a tab control. You refer the blog above for other methods and how to retrieve a particular tab from within the tab container control.

    ReplyDelete
  74. thanks, even after 2 year of posting very valuable :D

    -tortang talong

    ReplyDelete
  75. Hi sandeep,
    I want to validate three tabs with a single button click.Based upon,(which tab is currently active,i want to validate the current tab by the save button click).How can i get which tab is currently active?To be brief,I have three tabs with a save button.Validation should be based on the current tab.Give me some idea.

    With Advance thanks,
    Krithi

    ReplyDelete
  76. You can get the active tab using "get_activeTab" method. I would suggest to group each validation control into validation groups based on the tabs. This way you can easily validate each group. You can refer one of my blogs on validation group here.
    http://sandblogaspnet.blogspot.com/2009/09/calling-multiple-validation-group.html

    ReplyDelete
  77. Hi sandeep,
    I have four tabs,each tab have set of controls(more than 10).I have two buttons namely save and cancel.I didnt use validation controls ,instead i used javascript for validation.when i click the save button i want validate these four tabs before proceeding to next page..If any errors in any of these tabs,i want to show that also..Give me suggestion.

    With Advance thanks,
    S.Krithika

    ReplyDelete
  78. Hi Krithika,
    If you are only using javascript then it is further more easy. Group each tab' validation in their own function. Get the active tab and based on that call the respective tab' validation function or all the tab' validation. The code to get the active tab is as follows.
    var tabContainer = $get('<%=TAB_CONTAINER_ID.ClientID%>');
    if (tabContainer != undefined && tabContainer != null)
    {
    tabContainer = tabContainer.control;
    var activeTab = tabContainer.get_activeTab();
    //Your logic for tab validation goes here.
    }

    ReplyDelete
  79. Hi sandeep,

    Thanks For your reply.One more suggestion i need from you regarding javascript.I have a drop down control and text box in a tab(inside container).When a particular item is selected other than "Select",i want to make text box visible.How it can be achieved


    Advance Thanks,
    S.Krithika

    ReplyDelete
  80. Hi Krithika,
    Register a onClick javascript event on the dropdown.
    In the javascript do the following.
    function onChange() {
    var dropDown = document.getElementById('<%=DropDownList1.ClientID%>');
    var textBox = document.getElementById('<%=TextBox1.ClientID%>');
    textBox.style.visibility = dropDown.options[dropDown.selectedIndex].text.toLowerCase() == 'selected' ? 'hidden' : 'visible';
    }

    ReplyDelete
  81. Hi Sandeep,
    I have another problem in the tab focus .i have 4 tabs in a container.Each tab have set of contols(textbox,label,dropdown).whenever i select a item from dropdown,it will load and display the records from the DB in the corresponding controls.The problem is I have three sections in the page,
    1 st section is the panel(set of contols),middle is the container with tabs),and the lower is the panel display(set of conrols).whenver i select a item from the dropdown,its not focussing the tab,instead it focus at the top of the page..how it can be solved?
    Advance thanks
    By,
    S.Krithika

    ReplyDelete
  82. Hi Sandeep,
    I want to change the backgorund color of header in TabPanel based on the Database flag value.Could you please suggest.

    ReplyDelete
  83. Hi,
    To change the color of the header you will have override the CSS class associated with the tab. You can checkout the tabs.css file under the tabs folder of AjaxControlToolkit folder.

    ReplyDelete
  84. Hi Sandeep,
    I am wrote a javascript fuction to change the css dynamiaclly.Its working fine in FireFox but in Internet Explorer I am getting tabContainerControl as undefined.Below is the code.
    var tabContainer = document.getElementById('TabContainer1');
    if (tabContainer != 'undefined' && tabContainer != null) {
    var tabContainerControl = tabContainer.control;

    Please suggest.

    ReplyDelete
  85. Hi,
    Use $get instead of document.getElementById. Code is pasted below.
    var tabContainer = $get('TabContainer1');
    if (tabContainer != 'undefined' && tabContainer != null) {
    var tabContainerControl = tabContainer.control;

    ReplyDelete
  86. I tried using $get but still I am not getting "tabContainer.control".I want to use tabContainerControl.get_tabs() method.

    Could you please help me with this.

    ReplyDelete
  87. I would request you to send me the aspx or the whole code which you are using. Without which it will be difficult to suggest the problem.

    ReplyDelete
  88. Hi Sandeep,
    I create vb.net project, try catch function put on all web pages. Error will come, that error stored the one notepad document.
    Can u please help me how to send auto mail with that error document daily 6.00 pm.

    by
    Ariharan C

    ReplyDelete
  89. Hi Ariharan,
    To do you would probably write a windows service which will run on the background. Other than that I don't think there is a way to run a process which will endlessly and keep sending mail. One option would be thread but I doubt whether that can run endlessly...

    ReplyDelete
  90. I'll try... thanks Sandeep...

    by
    Ariharan C

    ReplyDelete
  91. This is the slowest website EVER ... thanks for the example though.

    ReplyDelete
  92. hi,
    Iam using a ajax tab container with three tabs.The whole page is inside update panel. Iam using javascript alert for error messages and javascript popoup window in the button of the tab.Whenever i click the button if error alert comes the whole tab panel dissaperas and reappears once i click ok of the alert. same in the case of popup too can u help me out.

    ReplyDelete
  93. Hi,
    It' difficult to say what could be the problem without seeing the code. I guess your page is getting posted again. If that is the case to prevent page postback add a "return false;" javascript statement in the click event of the button... Hope this solves your problem.

    ReplyDelete
  94. hi,

    Can u please help me how to send automatic email on daily with document. windows service code also ok.
    By
    Ariharan C

    ReplyDelete
  95. Hi Sandeep,
    I am new to ASP.NET. I am very much impressed with your blog. Even after going through all these posts, I am not able to figure out the exact method. I have a tabcontrol with 6 tabs and have Save button on the last tab. When the user clicks Save button , the validations fire. I am using valiation controls. If there are any errors, I want to set focus to first error among all the tabs. ( I mean the control can be either in tab1 or tab2 or tab4 etc but I want the focus to go to respective tab with error). Also I want to change the background color of all invalid items so that the user can easily notice.Could please help me with this?

    Thanks
    Lakshmi

    ReplyDelete
  96. Hi Lakshmi,
    I would suggest you to group your validation controls into validation groups. Group validation controls in each tab into their own group and on the click of the save button individually call each validation group. In this way it will be easy for you to make out which tab' validation group failed and you can set focus on that tab.
    To know more on how to call validation group please refer one of my blogs here http://sandblogaspnet.blogspot.com/2009/09/calling-multiple-validation-group.html.
    Hope this helps.

    ReplyDelete
    Replies
    1. Thanks for qucik response Sandeep. But I am not sure how do I move the focus to invalid item, I mean the user to be automatically moved to the first item of first validation group that errored out. Could you please give me an example of this?

      Delete
    2. Hi Lakshmi,
      The example code is there in the above pasted link. Once you know which group failed one option is to loop through all the validation control in that tab container and check the first one which failed. Use the controlToValidate property and set the focus on the control. If you still have doubt please send across the code which you are using so that I can find out where the problem lies..

      Delete
    3. Hi Sandeep,
      I couldn't get back to earlier as I got deviated from this to some other problem :). As I am still working on my intern, you might questions as stupid. But please bear with me. I could understand what you're trying to say theoritically but I having lots of questions while trying to code this. Through some forums I tried to post this flag into a hidden field. Based on the hiddenfield value I want the setfocus method to work. Do I need to set SetFocusOnError = True. How do I really do this? Please help me. I have implemented your code I do not see anything happending other than displaying error messages next to the fields as usual.

      Delete
    4. Sandeep,
      I am looking something similar to this blog http://sandblogaspnet.blogspot.com/2009/04/calling-validator-controls-from.html without using ValidatorCallout Extender. I want to using Validation and achieve something similar to this.

      Thanks
      Lakshmi

      Delete
  97. Hi Sandeep,

    If i use setfocus method for the Tabcontainer's tabpanel's textbox control, i couldnt see the cursor on textbox.But i can able to do change the color for that textbox. when i use the try catch for finding the exception, it says it did focus on that textbox, it never comes to catch, but actually i couldnt view it. Can you please help me on this issue?

    ReplyDelete
    Replies
    1. Hi,
      I think the problem may be b'coz you are setting the focus first on the the textbox and then making the tabcontainer active. First make the textbox containing the tabcontainer as the active one and then try to set focus on the textbox. Hope this helps...

      Delete
    2. Hi Sandeep,

      Thanks for your reply. I tried what you said activating the tabcontainer before setting focus, but no luck.I have a tabcontainer with 3 tabs, each with some textboxes and buttons, I just want to set focus on these controls from C# code behind, whenever a condition gets true, want to setfocus on the textbox instead of raising any event. Is that possible? Like, if the textbox is empty or having wrong input need to set focus, when you change the tab itself the focus should get inside of the text box. Is that possible?

      Delete
    3. I would rather ask for the code you are using. Please send across the code (aspx) page so that I can take a look into the actual problem.

      Delete
  98. Hi Sandeep,

    I'm logesh, I'm getting this error "htmlfile: Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus." only in IE8, all other browsers works fine.. I have been working on this for past 2 days.. let me know if yo could help me on this

    ReplyDelete
    Replies
    1. Hi Logesh,
      To help you I would need the aspx file you are using. Seeing the code will give me more idea on where the problem actually lies. If the code works on other browser then please confirm whether IE8 has any limitation in the code you are using.

      Delete
  99. I fixed it.. IE8 for some reason din support tabcontrol from of latest ajax control tool kit.. I rolled back to prior version.. everything worked fine... but I do have a new problem.. I'm validating my website against all the browsers.. In safari when I first load the site.. the cross bar menu doesn't get loaded.. only when I click over an item.. the page gets loaded.. What shall i do ! ?

    ReplyDelete
  100. Please send me the tab-container full code ..i will be thankful to you .i am new to asp.net .please help me my email :connect2hadi@gmail.com

    ReplyDelete
    Replies
    1. Hi,
      The blog was published 2009 and I am afraid I don't have the solution. All the code is pasted in the blog. You can copy and paste it in VS and run it. As long as you have your environment configured properly I don't think you will have any problem.

      Delete
  101. Hi, Sandeep... i have the problem with Tabs Active position, when i click a tab in Tabcontainer (Master Page) to navigate to a new page through Response.Redirect("Newpage.aspx"), it always select the 1st tab, while i clicked the 2, or 3rd. i want to active the particular tab i selected. please help no script is working :(

    ReplyDelete
  102. Hello Sandeep,
    i have a problem with java script tabs...
    i want to know which tab is active,which i can use in my C# code so that i can do the coding on the click event of the button in c#...Plz rply soon..
    Thanx

    ReplyDelete
  103. Hi Sandeep,
    i have a problem with ajax tab control.
    In ajax tab control i have two tabs.in first and second tab i used dropdown lists and set the autopostback true.when i select the dropdown list in second tab it moves to the first tab.
    how to retain on the selected tab.
    Please help me.
    Thanks.

    ReplyDelete
  104. the above mentioned javascript is not working
    i am using ajax tool kit verssion 3.5
    i am dynamically populating the tab and i want to get the
    name of active tab via javascript but when i used the above mentioned code i found the error that object doesnot support this property or method...
    please help i am stuck to it for the pas 1 day....
    i have also included the assemply tag for ajaxtoolkit in my code

    ReplyDelete
  105. Hi how can I achieve the following requirement, assume I have 3 tabs in the first tab I am having some personal information, 2nd job details and address in 3rd tab.

    If user tries to move to any one of the tab with out saving the personal information it should pop up a message saying do you wish to continue. If yes navigate to next tab if not stay in the current tab

    ReplyDelete
  106. Hi How can I make tab read only that unclickable while lazy loading is loading content by javascript.

    ReplyDelete
  107. hi
    i have a problem with ajax tab control.

    how to know the number of control (count of control ) in active tab
    Please help me.
    Thanks.

    ReplyDelete
    Replies
    1. client side javascript coading
      Thanks .....

      Delete
  108. hi sandeep

    I have a problem with ajax html editor extender,

    how to save the editor extender html preview into the database

    can you help me out of this

    ReplyDelete
  109. hello frd , i have problem in tab container in ajax toolkit

    when page load it load start from middle of page where my tab pannel has stay.. !

    ReplyDelete
  110. hii friends i have problem in tab container on page load i set textbox1 focus but i am trying focus on next textbox when pressing enterkey in tabcontainer i have two tab and one tab has four textbox so i want trransfer focus next textbox by pressing enterkey plz help me

    ReplyDelete
  111. hii all I have put a text-box,button and grid-view inside a ajax tab panel.The program will display the contents in grid view after click on button.i have written all the code and this code is working fine without using tab panel but when i added tab panel the button click does not fire at all please help me.

    ReplyDelete
  112. How can i disable click on the tabs that leads to the tab change on clicking on the header?

    i want to navigate the tabs using button inside the tab panel. And i am able to do that currently.

    ReplyDelete
  113. This comment has been removed by the author.

    ReplyDelete

Please provide your valuable comments.