Enable or Disable All Tabs Except the Selected Tab inside the Telerik RadTabStrip

We will explore the JavaScript code, by which we can easily Enable or Disable all the Tabs inside a Telerik RadTabStrip except the SelectedTab. In my previous Blog, we explored how to Enable or Disable all the Tabs. Now let’s see how we can just do this for all the Tabs except the current Tab.

How this is helpful?

This kind of requirement comes, when you have some business logic in a Tab (without saving the data), other Tabs can’t be accessible. Take one example, like, when you are registering something step by step. So, in first Tab, you will ask the User to enter some details and when he/she enters and hits register, you Enable all other Tabs, else just Disable.

How to?

If the Tab Text does not match with the SelectedTab‘s Text, then Disable it. Simple !!!

function DisableOtherTabs(){
    // Get the Tab Strip.
    var tabStrip = $find("<%= yourTabStripID.ClientID %>");

    // Get all the Tabs.
    var tabs = tabStrip.get_tabs();

    // Get Selected Tab.
    var selectedTab = tabStrip.get_selectedTab();

    // Now loop through all the Tabs and Disable one by one.
    for(var i = 0; i < tabStrip.get_allTabs().length; i++){
        // If the Tab Text does not match with the Selected Tab's Text, then Disable it. Simple !!!
        if(tabs.getTab(i).get_text().toUpperCase() != selectedTab.get_text().toUpperCase()){
            tabs.getTab(i).disable();
        }
    }
}

Thanks !!!

For taking time and reading the Blog. If you find it useful, then share within your circle, by pressing the Social Icons.

Enable Disable all Tabs inside Telerik RadTabStrip

We will explore the JavaScript code, by which we can easily Enable or Disable all the Tabs inside a Telerik RadTabStrip.

Read the comments inside the code blocks to know how the code works.

Enable All Tabs

function EnableAllTabs(){
    // Get the Tab Strip.
    var tabStrip = $find('<%= yourTabStripID.ClientID >');
    
    // Get all the Tabs.
    var tabs = tabStrip.get_tabs();

    // Now loop through all the Tabs and Enable one by one.
    for(var i = 0; i < tabStrip.get_allTabs().length; i++){
        tabs.getTab(i).enable();
    }
}

Disable All Tabs

function DisableAllTabs(){
    // Get the Tab Strip.
    var tabStrip = $find('<%= yourTabStripID.ClientID >');
    
    // Get all the Tabs.
    var tabs = tabStrip.get_tabs();

    // Now loop through all the Tabs and Disable one by one.
    for(var i = 0; i < tabStrip.get_allTabs().length; i++){
        tabs.getTab(i).disable();
    }
}

ASP.NET GridView Client Side Validation

Email Validation Failed Alert

Email Validation Failed Alert


We will explore the technique in jQuery to validate the ASP.NET GridView.

Setting up the GridView First

On aspx Page

We will show following fields in GridView.

  • Name – TextBox
  • Age – TextBox
  • Email – TextBox
  • Date of Birth – TextBox (with jQuery DatePicker)
  • Gender – RadioButtonList

For each field, we will have one TemplateField with

  1. ItemTemplate (shows when Grid is loaded) – Inside this, a Label to show the value.
  2. EditItemTemplate (shows when Grid is in Edit Mode) – Inside this, actual TextBox or RadioButtonList.
<asp:GridView ID="gvTestValidations" runat="server" AutoGenerateColumns="false" OnRowEditing="gvTestValidations_RowEditing"
	OnRowUpdating="gvTestValidations_RowUpdating" OnRowCancelingEdit="gvTestValidations_RowCancelingEdit">
	<Columns>
		<asp:TemplateField HeaderText="Name">
			<ItemTemplate>
				<asp:Label ID="lblName" runat="server" Text='<%#Bind("Name") %>'></asp:Label>
			</ItemTemplate>
			<EditItemTemplate>
				<asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name") %>' />
			</EditItemTemplate>
		</asp:TemplateField>
		<asp:TemplateField HeaderText="Age">
			<ItemTemplate>
				<asp:Label ID="lblAge" runat="server" Text='<%#Bind("Age") %>'></asp:Label>
			</ItemTemplate>
			<EditItemTemplate>
				<asp:TextBox ID="txtAge" runat="server" Text='<%#Bind("Age") %>' />
			</EditItemTemplate>
		</asp:TemplateField>
		<asp:TemplateField HeaderText="Email">
			<ItemTemplate>
				<asp:Label ID="lblEmail" runat="server" Text='<%#Bind("Email") %>'></asp:Label>
			</ItemTemplate>
			<EditItemTemplate>
				<asp:TextBox ID="txtEmail" runat="server" Text='<%#Bind("Email") %>' />
			</EditItemTemplate>
		</asp:TemplateField>
		<asp:TemplateField HeaderText="Date Of Birth">
			<ItemTemplate>
				<asp:Label ID="lblDOB" runat="server" Text='<%#Bind("DOB") %>'></asp:Label>
			</ItemTemplate>
			<EditItemTemplate>
				<asp:TextBox ID="txtDOB" runat="server" Text='<%#Bind("DOB") %>' />
			</EditItemTemplate>
		</asp:TemplateField>
		<asp:TemplateField HeaderText="Gender">
			<ItemTemplate>
				<asp:Label ID="lblGender" runat="server" Text='<%#Bind("Gender") %>'></asp:Label>
			</ItemTemplate>
			<EditItemTemplate>
				<asp:RadioButtonList ID="rblGender" runat="server" SelectedValue='<%#Bind("Gender") %>'>
					<asp:ListItem Value="Male">Male</asp:ListItem>
					<asp:ListItem Value="Female">Female</asp:ListItem>
				</asp:RadioButtonList>
			</EditItemTemplate>
		</asp:TemplateField>
		<asp:CommandField ShowEditButton="true" HeaderText="Edit" />
	</Columns>
</asp:GridView>

On aspx.cs Page

As I am not using Database, so to bind the GridView, we can have one DataTable property stored in ViewState. We will edit, update to the ViewState Table and bind that to the GridView. Inside the Page Load, we will declare hard-coded rows and add them to DataTable. Then bind that to the Grid.

// This ViewState DataTable Property holds the GridView Data.
DataTable dtGridData
{
    get
    {
        return (DataTable)ViewState["dtGridData"];
    }
    set
    {
        ViewState["dtGridData"] = value;
    }
}

protected void Page_Load(object sender, EventArgs e)
{
	if (!IsPostBack)
	{
		// Add Column for the DataTable.
		DataTable dt = new DataTable();
		dt.Columns.Add(new DataColumn("Name"));
		dt.Columns.Add(new DataColumn("Age"));
		dt.Columns.Add(new DataColumn("Email"));
		dt.Columns.Add(new DataColumn("DOB"));
		dt.Columns.Add(new DataColumn("Gender"));

		// Add Rows to DataTable.
		DataRow dr = dt.NewRow();
		dr["Name"] = "Deepak Mahapatra";
		dr["Age"] = 24;
		dr["Email"] = "abc@anything.com";
		dr["DOB"] = "09/28/1990";
		dr["Gender"] = "Male";

		dt.Rows.Add(dr);

		dr = dt.NewRow();
		dr["Name"] = "Dillip Das";
		dr["Age"] = 24;
		dr["Email"] = "def@anything.com";
		dr["DOB"] = "10/02/1990";
		dr["Gender"] = "Male";

		dt.Rows.Add(dr);

		dr = dt.NewRow();
		dr["Name"] = "Tadit Dash";
		dr["Age"] = 24;
		dr["Email"] = "ghi@anything.com";
		dr["DOB"] = "07/05/1990";
		dr["Gender"] = "Male";

		dt.Rows.Add(dr);

		// Assign the DataTable to dtGridData, so that it is stored in ViewState.
		// After that, bind the GridView.
		dtGridData = dt;
		BindGrid();
	}
}

private void BindGrid()
{
	gvTestValidations.DataSource = ViewState["dtGridData"];
	gvTestValidations.DataBind();
}

What’s on Browser?

Initial Load

GridView on Browser

GridView on Browser

On Row Edit Button Click

First Row in Edit Mode

First Row in Edit Mode

Now, the Actual Show Begins !!!

We will do following validation…

  • For Age Field – Only Allow Numbers
  • For Email Field – Email Validation

You can do more validations, you just need to learn how to do it.

So, How to?

Logic is that, inside the document Ready Event, we will try to find all the Age TextBoxes and Email TextBoxes inside the GridView and handle the keydown and change events respectively.

For Age TextBox

The highlighted code lines are important.

$("#gvTestValidations tr input[id*='txtAge']").each(function () {
	$(this).keydown(function (event) {
        // Just to find all non-decimal characters and replace them with blank.
		$(this).val($(this).val().replace(/[^\d].+/, ""));

		var charCode = (event.which) ? event.which : event.keyCode;
		if (charCode > 31 && (charCode < 48 || charCode > 57)) {
			event.preventDefault();

			isValidated = false;
		}
		else { isValidated = true; }
	});
});

The first important line is…

$("#gvTestValidations tr input[id*='txtAge']")

This is actually searching for all the TextBoxes inside the Grid with the help of Attribute Contains Selector [name*="value"].
Then the following code attaches the keydown Event with all those matched Age TextBoxes.

$(this).keydown(function (event) {
    // Validation code here...
});

For Email TextBox

The same logic is used for Email TextBox. The only difference is that we are handling the change Event here instead of keydown Event.

$("#gvTestValidations tr input[id*='txtEmail']").each(function () {
	$(this).change(function (event) {
		if (!validateEmail($(this).val())) {
			alert("Email not in correct format.");
			$(this).addClass('errorClass');
			event.preventDefault();

			isValidated = false;
		}
		else {
			$(this).removeClass('errorClass');

			isValidated = true;
		}
	});
});

NOTE: The CSS class “errorClass” is used to make Email TextBox Border Red-Coloured, when validation fails.

One more interesting thing…

We are also restricting User to Update one record, if the row is not validated. Suppose, User has typed one wrong Email Id and then directly hits the Update Button, so it won’t allow the User to Update and show one message. For that, we are using the variable isValidated, which you have already seen inside the code.
We are just checking the isValidated value inside the Update Button click and taking action according to that. Again the same logic, which is searching all the links and finds the Button, which is having Text as “Update” and fires its click Event.

$("#gvTestValidations a").each(function () {
	if ($(this).text() == "Update") {
		$(this).click(function (event) {
			if (!isValidated) {
				alert("There are issues with input fields. Please correct and then try.");
				return false;
			}
			else { return true; }
		});
	}
});
Update Button not working if Validation Fails

Update Button not working if Validation Fails

Thanks !!!

For taking time and reading the Blog. Download the Project and play with it. If you find it useful, then share within your circle, by pressing the Social Icons.

Why GridView RowUpdating Event is not giving the updated values?

Debugger Inside GridView RowUpdating Event

Debugger Inside GridView RowUpdating Event


This is a most common question in Forums. We will find the actual cause, for which the RowUpdating Event behaves abnormal.

Walk Through

  1. Add a GridView in aspx page and define all its required properties and Events.

    <asp:GridView ID="gvTestGrid" runat="server" AutoGenerateColumns="false" 
                  OnRowCancelingEdit="gvTestGrid_RowCancelingEdit"
                  OnRowEditing="gvTestGrid_RowEditing" 
                  OnRowUpdating="gvTestGrid_RowUpdating">
        <Columns>
            <asp:BoundField DataField="Column1" HeaderText="Some Column"/>
            <asp:CommandField ShowEditButton="true" />
        </Columns>
    </asp:GridView>
    
  2. Bind the GridView from back end. For our example, we will bind one DataTable.
    private void BindGrid()
    {
        // Add Column for the DataTable.
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Column1"));
    
        // Add Rows to DataTable.
        for (int i = 1; i < 5; i++)
        {
    	    DataRow dr = dt.NewRow();
    	    dr["Column1"] = "Old Value" + i;
    	    dt.Rows.Add(dr);
        }
    
        gvTestGrid.DataSource = dt;
        gvTestGrid.DataBind();
    }
  3. Define the GridView Events for Edit and Update operation.
    protected void gvTestGrid_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //Set the edit index.
        gvTestGrid.EditIndex = e.NewEditIndex;
    
        //Bind data to the GridView control.
        BindGrid();
    }
    
    protected void gvTestGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //Get the new Values.
        GridViewRow row = gvTestGrid.Rows[e.RowIndex];
        string column1Value = ((TextBox)row.Cells[0].Controls[0]).Text;
    
        // Code to update the DataSource.
        //.....
    
        //Reset the edit index.
        gvTestGrid.EditIndex = -1;
    
        //Bind data to the GridView control.
        BindGrid();
    }
    
    protected void gvTestGrid_RowCancelingEdit(object sender, 
                                               GridViewCancelEditEventArgs e)
    {
        //Reset the edit index.
        gvTestGrid.EditIndex = -1;
    
        //Bind data to the GridView control.
        BindGrid();
    }
    
  4. GridView on Browser would look like…

    GridView on Browser

    GridView on Browser

    Now, Let’s Test

    To test the Edit and Update features, let’s click on Edit Button in any Row. We can see that GridView adds TextBoxes in all the cells of that Row immediately. It also shows you Update and Cancel Buttons where it was previously showing Edit Button.
    Let’s do some editing in the cells and click Update Button.

    GridView Cell Showing Updated Value

    GridView Cell Showing Updated Value


    It hits the breakpoint, we have set inside the RowUpdating Event. If we move our mouse on to the variables, which hold the cell values, we can see the old value instead of new updated value (Refer the debugging Screen Shot at the Top). So, we are stuck now, this is the bug.

    What to do now?

    Don’t panic. We need to find out what exactly in code is helping RowUpdating Event to give old values. So, the most wild guess is that, something is causing the Grid to bind again before RowUpdating Event, as we initially did during load.

    If you remember, in Step-2, we did bind the Grid, which is actually called on the Page Load like…

    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }
    

    According to the Event Life Cycle, when any Control Event is fired (here Grid RowUpdating), it first goes to Page Load. As it is coming to Page Load, so it calls the Bind method again and re-binds the Grid. Now, it goes to RowUpdating Event, but the updated values are lost because Grid is already reset in Page Load.

    So, How to Resolve?

    IsPostBack() is the answer. We have to check if the Page is posted back or not. If not, then we will bind the Grid.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    

    Go and Share this with your friends

    This issue sometimes kills time. So, don’t wait, just share with everybody you know, who can understand this. Also provide your valuable feedback here. Thanks for reading.

ASP.NET Repeater with jQuery Slider

Image Slider with Repeater

Image Slider with Repeater


In this Blog, we will learn how to integrate one jQuery Slider Plugin with the ASP.NET Repeater Control.

Background

There was a question on implementation of slider with ASP.NET DataList Control and the guy who posted that was facing issues. The issue was actually due to the DataList control, which was rendering as HTML tables breaking the default jQuery Slider functionality. After researching a bit, I found that, it is very easy to implement this with the ASP.NET Repeater control. Let’s go step by step and learn.

Step by Step

Step-1 : Download jQuery Slider Plugin

You can take any jQuery Slider, but you need to see how exactly it allows contents inside it. For this example, we will be using the Elastislide. Hit the “Download Source” button on the page to download the zip file containing the Plugin files. We will try to implement the demo given here (Example 1).

Let’s extract the zip file. You will have something like this inside the Extracted folder.

Extracted jQuery Slider Files

Extracted jQuery Slider Files


So, here we can find all related JavaScript, CSS and images used for the Demos. The demo, which we will implement with Repeater is shown inside the index.html (highlighted in image). You can directly run and see in browser.

Step-2 : Analysis of Demo HTML Page

JavaScript and CSS Files Included

In Head section…

<link rel="stylesheet" type="text/css" href="css/demo.css" />
<link rel="stylesheet" type="text/css" href="css/elastislide.css" />
<link rel="stylesheet" type="text/css" href="css/custom.css" />
<script src="js/modernizr.custom.17475.js"></script>

In Body Section…

<script type="text/javascript" 
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script type="text/javascript" src="js/jquerypp.custom.js"></script>
<script type="text/javascript" src="js/jquery.elastislide.js"></script>

So, we will also include these files in our aspx page.

HTML Markup for Image Slider

If you open and see the index.html page, you will find a HTML structure which loads all the images. (I have removed the not needed headers and other HTML.)

<div class="container demo-1">
	<div class="main">
		<!-- Elastislide Carousel -->
		<ul id="carousel" class="elastislide-list">
			<li><a href="#"><img src="images/small/1.jpg" alt="image01" /></a></li>
			<li><a href="#"><img src="images/small/2.jpg" alt="image02" /></a></li>
			<li><a href="#"><img src="images/small/3.jpg" alt="image03" /></a></li>
			<li><a href="#"><img src="images/small/4.jpg" alt="image04" /></a></li>
			<li><a href="#"><img src="images/small/5.jpg" alt="image05" /></a></li>
			<li><a href="#"><img src="images/small/6.jpg" alt="image06" /></a></li>
			<li><a href="#"><img src="images/small/7.jpg" alt="image07" /></a></li>
			<li><a href="#"><img src="images/small/8.jpg" alt="image08" /></a></li>
			<li><a href="#"><img src="images/small/9.jpg" alt="image09" /></a></li>
			<li><a href="#"><img src="images/small/10.jpg" alt="image10" /></a></li>
			<li><a href="#"><img src="images/small/11.jpg" alt="image11" /></a></li>
			<li><a href="#"><img src="images/small/12.jpg" alt="image12" /></a></li>
			<li><a href="#"><img src="images/small/13.jpg" alt="image13" /></a></li>
			<li><a href="#"><img src="images/small/14.jpg" alt="image14" /></a></li>
			<li><a href="#"><img src="images/small/15.jpg" alt="image15" /></a></li>
			<li><a href="#"><img src="images/small/16.jpg" alt="image16" /></a></li>
			<li><a href="#"><img src="images/small/17.jpg" alt="image17" /></a></li>
			<li><a href="#"><img src="images/small/18.jpg" alt="image18" /></a></li>
			<li><a href="#"><img src="images/small/19.jpg" alt="image19" /></a></li>
			<li><a href="#"><img src="images/small/20.jpg" alt="image20" /></a></li>
		</ul>
		<!-- End Elastislide Carousel -->
	</div>
</div>

This structure is most important, because the classes added to the HTML controls are used inside the CSS and JavaScript files.
So, we just need to replace the “list items (li)” inside the “Unordered Lists” with Repeater Items, which eventually would look like the same structure and render all the image URLs inside List Items.

Step-3 : Create a Web Application and Add one aspx Page

After adding the aspx page to the Project, now we need to copy the js, css files and images from the “Downloaded Plugin” folders. So, Solution Explorer would look like…

Solution Explorer View

Solution Explorer View


NOTE : We have maintained the exact folder structure as in the Downloaded Plugin. Only “small” folder inside “images” folder is copied with another the “nav.png” image used for “previous next” buttons.

Step-4 : Let’s Design the aspx Page

Basically, we will copy the HTML present in index.html page and update it by adding one Repeater.
Now, the div would look like…

<div class="container demo-1">
	<div class="main">
		<ul id="carousel" class="elastislide-list">
			<asp:Repeater ID="mylist" runat="server">
				<ItemTemplate>
					<li><a href="#">
						<asp:Image ID="Image1" runat="server" ImageUrl='<%# "images/small/" + Eval("image")%>' />
					</a></li>
				</ItemTemplate>
			</asp:Repeater>
		</ul>
	</div>
</div>

:: Here ImageUrl Property is a combination of folders path and image name. Image Name is dynamically bound from the Datasource (explained in the next step), EVAL is used for this purpose only.
Next we will add the JavaScript and CSS files in the Page just like it appears in the index.html Page.
Now, most important thing is to add the following script inside the body.

<script type="text/javascript">
    $('#carousel').elastislide();
</script>

This code actually invokes the Slider to work. carousel is the id of the ul (Unordered list) element in HTML. This elastislide(); method is present in the Plugin js.

Step-5 : Bind the Repeater from Code Behind

protected void Page_Load(object sender, EventArgs e)
{
	if (!Page.IsPostBack)
	{
		BindRepeater();
	}
}

/// <summary>
/// This method binds the Image Slider.
/// </summary>
private void BindRepeater()
{
	DataTable dt = new DataTable();
	dt.Columns.Add("image");

	for (int i = 1; i <= 20; i++)
	{
		dt.Rows.Add(i + ".jpg");
	}

	mylist.DataSource = dt;
	mylist.DataBind();
}

This code is very simple. It binds the Repeater from a DataTable, which contains rows as image names. Image names are 1.jpg, 2.jpg till 19.jpg. You can put your image binding logic here to bind the Repeater.

Feedback Equips Me !!!

Please put your thoughts on the Project by commenting below the Blog. Like and Share, if you liked it.

Why DropDownList SelectedValue not working inside SelectedIndexChanged Event?

Debugger Inside DropDown SelectedIndexChanged Event

Debugger Inside DropDown SelectedIndexChanged Event


In this Blog, we will explore one interesting Bug, which ASP.NET Developers encounter sometimes.

Bug

DropDownList SelectedValue inside SelectedIndexChanged Event does not give the current Selected Value, rather it gives the Default Value or first Option Value.

Walk Through

  1. Let’s declare a DropDownList first.

    <asp:DropDownList ID="ddlDropDownId" runat="server" AutoPostBack="true" 
                      OnSelectedIndexChanged="ddlDropDownId_SelectedIndexChanged">
    </asp:DropDownList>
    
  2. Now to bind the DropDownList, we will write one function like below…
    private void BindDropDownList()
    {
        // Declare a Dictionary to hold all the Options with Value and Text.
        Dictionary<string, string> options = new Dictionary<string, string>();
        options.Add("-1", "Select Option");
        options.Add("1", "Option 1");
        options.Add("2", "Option 2");
        options.Add("3", "Option 3");
        options.Add("4", "Option 4");
        options.Add("5", "Option 5");
    
        // Bind the Dictionary to the DropDownList.
        ddlDropDownId.DataSource = options;
        ddlDropDownId.DataTextField = "value";
        ddlDropDownId.DataValueField = "key";
        ddlDropDownId.DataBind();
    }
    
  3. So, when you run the Page, it would show you the DropDownList on the Page with the Options defined.
    DropDownList on Browser

    DropDownList on Browser

  4. When you select an Option from the DropDownList, it hits the SelectedIndexChanged Event in the Code Behind. If you need to get the SelectedValue, then you will write…
    protected void ddlDropDownId_SelectedIndexChanged(object sender, EventArgs e)
    {
        string value = ddlDropDownId.SelectedValue;
    }
    
  5. Now Here Comes the Main Issue

    When we put a debugger inside the Event and checked, irrespective of the selection of any Option, it always gives you the first Option Value that is “-1″. Refer the debugging Screen Shot at the Top.
    And there is no doubt on the first Option value “-1″, as we can clearly see from the Source HTML of the DropDownList. See highlighted Option in the image below.

    DropDownList Source HTML

    DropDownList Source HTML

    Any Hint Here?

    As we are getting the default value or the first value always, so the guess is that, something is causing the DropDownList to bind again when we select an Option.

    Let’s Find Out !!!

    In the Walk Through Steps, I said about the function BindDropDownList(), which binds the DropDownList. But we need to check where exactly it is getting called. As the DropDownList shows when the Page is Loaded, so it must be present inside the Page Load Event.

    protected void Page_Load(object sender, EventArgs e)
    {
        BindDropDownList();
    }
    

    Now, according to the Event Life Cycle rules, when you select an Option from DropDownList, it Posts Back and goes to Page Load Event first and then it comes to the SelectedIndexChanged Event.
    That means, it comes to the Page Load again on selection of any Option and calls the BindDropDownList(). Thus, the DropDownList is bounded again, before it goes to the SelectedIndexChanged Event. As the DropDownList is bound again, so the SelectedValue is now the first Option Value, which is “-1″ (for “Select Option”).

    Fix?

    You might have got the answer. That is IsPostBack Property.

    Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.

    It tells you whether you are loading the Page for first time or is it a Post Back due to any Event. Modified code would look something like below.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDownList();
        }
    }
    

    So, Be Careful and Share This to Save Someone’s Day !!!

    You might have played with all the codes in your Page to find out the issue, but at last you come to know that it was because you forgot to check IsPostBack Property. So, Like and Share this with your friends, so that anybody who is unable to find the problem, finally let out a sigh.

Change Background Color of Ajax HtmlEditorExtender using ColorPickerExtender

[Demo] Change Background Color of HtmlEditorExtender

[Demo] Change Background Color of HtmlEditorExtender


In this Blog, we will learn to change the Background Color of Ajax HtmlEditorExtender using ColorPickerExtender.

Background

There was an question, which eventually gave birth to this Blog.

Here comes the Logic

We have already discussed the Logic in one of the previous Blog Set Content inside AJAX HTMLEditor and EditorExtender using JavaScript. We just need to find out the Edit Panel, that is the div, which is actually showing data for HtmlEditorExtender. Then we can easily assign Selected Color of ColorPickerExtender to that div.

<div contenteditable="true"
     id="txtEditorDemo$HtmlEditorExtenderBehavior_ExtenderContentEditable"
     style="height: 80%; overflow: auto; clear: both;"
     class="ajax__html_editor_extender_texteditor">
</div>

Okay ! Let’s get our feet wet

Get the ColorPickerExtender Selected Color

We can easily get the Selected color by handling the OnClientColorSelectionChanged Event of ColorPickerExtender. We can call a JavaScript function on this Event. Let’s see the markup.

<asp:ColorPickerExtender runat="server" 
                         TargetControlID="txtSelectColor"
                         SampleControlID="sampleBodyColor"
                         PopupButtonID="txtSelectColor" 
                         OnClientColorSelectionChanged="colorChanged">
</asp:ColorPickerExtender>

So, the JavaScript function is colorChanged(). Following code would alert you the Selected Color.

function colorChanged(sender) {
    alert(sender.get_selectedColor());
}
Selected Color on Alert Box

Selected Color on Alert Box

Now, let’s get the HtmlEditorExtender and change its Background Color

There are two ways to do this.

  • Using Sys.Application $find Method

    First find the HTMLEditorExtenderusing ID, then assign the Selected Color to the Background Color Property of its EditableDiv.

    var htmlEditorExtender = $find("<%= heeEditorDemo.ClientID %>");
    htmlEditorExtender._editableDiv
                      .style
                      .backgroundColor = '#' + sender.get_selectedColor();
    
  • Using jQuery Class Selector

    Get the HTMLEditorExtender by its class name ajax__html_editor_extender_texteditor. Then set its Background Color by .css() Method.

    var htmlEditorExtender = $('.ajax__html_editor_extender_texteditor');
    htmlEditorExtender.css('background-color', '#' + sender.get_selectedColor());
    

NOTE

Here we have appended ‘#’ before the Selected Color. That is because Selected Color is only a Hex Number without the prefix ‘#’, as we can see on the screenshot above, where we have alerted the Selected Color.

Thanks !!!

For taking time and reading the Blog. If you find it useful, then share within your circle, by pressing the Social Icons.