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" 
            <asp:BoundField DataField="Column1" HeaderText="Some Column"/>
            <asp:CommandField ShowEditButton="true" />
  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;
        gvTestGrid.DataSource = dt;
  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.
    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.
    protected void gvTestGrid_RowCancelingEdit(object sender, 
                                               GridViewCancelEditEventArgs e)
        //Reset the edit index.
        gvTestGrid.EditIndex = -1;
        //Bind data to the GridView control.
  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)

    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)

    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.


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" 
<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>
		<!-- End Elastislide Carousel -->

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">
					<li><a href="#">
						<asp:Image ID="Image1" runat="server" ImageUrl='<%# "images/small/" + Eval("image")%>' />

:: 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">

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)

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

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

	mylist.DataSource = dt;

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.


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" 
  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";
  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)

    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").


    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)

    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.


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"
     style="height: 80%; overflow: auto; clear: both;"

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" 

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

function colorChanged(sender) {
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 %>");
                      .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());


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.

Attach Event to all the TextBoxes in a WebPage

All TextBoxes except Email type allow only numbers

All TextBoxes except Email type allow only numbers

Update on 25 April 2014

Blog continues…

Inspired from a Question, I am blogging about a simple technique to attach KeyPress Event to all the TextBoxes of a WebPage.

And what is the Technique?

  • Loop through all the Controls in the WebPage
  • Find which are TextBoxes
  • For those Boxes, attach KeyPress Event

We will do it using JavaScript.

Can you elaborate each step?

Why not !!! Let's explore.

Loop through all the Controls in the WebPage

var allInputs = new Array();

// store collection of all <input/> elements
allInputs = document.getElementsByTagName('input');

So, allInputs array would contain all the input elements on the WebPage.

Find which are TextBoxes

for (i = 0; i < allInputs.length; i++) {
    // loop through and find <input type="text"/>
    if (allInputs[i].type == 'text') {
        // This is a TextBox. Here we can attach any Event.

Here we are looping through all the inputs and checking if its type is text. If satisfied, it is a TextBox.
In that if clause, we can attach any Event we need. We will attach the KeyPress Event in the next Step.

For those Boxes, attach KeyPress Event

We will attach KeyPress Event as an example. For that, we will use jQuery KeyPress.

for (i = 0; i < allInputs.length; i++) {
    // loop through and find <input type="text"/>
    if (allInputs[i].type == 'text') {
        // This is a TextBox. Here we can attach any Event.
        // Let's attach KeyPress Event to the TextBox.
        $(allInputs[i]).keypress(function (event) {
            if (!isNumber(event)) {

Here, we attached the KeyPress Event and inside that Event, we are calling one function isNumber(event). If the pressed key is not a number, it would ignore as event.preventDefault() comes into action, else it will allow.


The function isNumber(event) just checks, if the pressed key is a numeric key or not. Refer the Demo link given below to see the code for this function.

See this in action

Demo - Here.

Update, Improvements and Quicker jQuery Approach

Thanks to Kshirodra Meher and Subhajit Datta for the valuable suggestions.

What they suggested?

In our first step, we looped through all the TextBoxes present in the Page, which can be optimized with a simpler jQuery block coded below.

$("input[type=text]").bind("keypress", function (e) {
    if (!isNumber(e)) {
        return false;

So, the main game changer here is the Selector $("input[type=text]"). It selects all the inputs of type text. To know more click - Attribute Equals Selector [name="value"].
We have also restricted the paste event on the TextBoxes because it was allowing all characters into the box.

$("input[type=text]").bind("paste", function (e) {
    return false;

New Demo


Share your thoughts !!!

If you like the Blog, share among your friends. Feel free to comment, if you have any doubts or queries.

Bind DropDownList from DataTable using AJAX WebMethod

DropDownList Bound from Ajax WebMethod

DropDownList Bound from Ajax WebMethod

We will see one Example to bind one DropDownList using jQuery Ajax and C# WebMethod.


Easy !!!

  • Add a WebMethod to Code Behind page
  • Call to that WebMethod from aspx Page
  • Bind the DropDownList when call succeeds

Let's see the code


Here we are just creating a Dummy DataTable and converting it to XML.

/// <summary>
/// This WebMethod returns the XML for a DropDownList having value and text.
/// </summary>
/// <param name="tableName">string: Name of the Table having DropDownList items.</param>
/// <returns>string: XML containing all the items.</returns>
public static string GetDropDownItems(string tableName)
    // Create a dummy DataTable.
    DataTable dt = new DataTable(tableName);
    dt.Rows.Add("0", "Item 0");
    dt.Rows.Add("1", "Item 1");
    dt.Rows.Add("2", "Item 2");
    dt.Rows.Add("3", "Item 3");
    dt.Rows.Add("4", "Item 4");

    // Convert the DataTable to XML.
    string result;
    using (StringWriter sw = new StringWriter())
        result = sw.ToString();

    return result;

JavaScript GetDropDownData function

The following function would do a jQuery Ajax call for the WebMethod and bind the Data to the DropDownList.

function GetDropDownData() {
	// Get the DropDownList.
	var ddlTestDropDownListXML = $('#ddlTestDropDownListXML');
	// Provide Some Table name to pass to the WebMethod as a paramter.
	var tableName = "someTableName";

		type: "POST",
		url: "BindDropDownList.aspx/GetDropDownItems",
		data: '{tableName: "' + tableName + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (response) {
			// Now find the Table from response and loop through each item (row).
			$(response.d).find(tableName).each(function () {
				// Get the OptionValue and OptionText Column values.
				var OptionValue = $(this).find('OptionValue').text();
				var OptionText = $(this).find('OptionText').text();
				// Create an Option for DropDownList.
				var option = $("<option>" + OptionText + "</option>");
				option.attr("value", OptionValue);

		failure: function (response) {

Important: We are passing one parameter tableName to the WebMethod, which will be the Dummy Table Name and after conversion to XML, it becomes parent of each Row. Refer the following Screenshot of returned XML Schema as seen inside Firebug Console.

XML returned from WebMethod

XML returned from WebMethod

We can see that someTableName is one one node containing the OptionText and OptionValue of a particular Item. These are actually Rows of the Dummy DataTable before conversion to XML.

Your Inputs !

Will be highly appreciated. Please feel free to comment. If you like the Blog, share this among your friends and colleagues.

Microsoft ASP.NET MVP Award 2014

Microsoft MVP 2014 Mail

Microsoft MVP 2014

[Update on 4th April]
My best birthday Gift on 4th April by my CEO Mr. Chinmoy Panda. He narrates my story in his own words. Celebrating Awesomeness

Be awesome. Be Tadit.

[Blog Continues]
Thank God, I was not fooled on April 1. :)

I am really happy to announce that I have been awarded as one of the “Most Valuable Professionals” in ASP.NET/IIS category. This is the very first time I am getting awarded by Microsoft for my Technical Community Activities.

What is Microsoft MVP?

Answer : Click here to know more.

The Microsoft Most Valuable Professional (MVP) Award is our way of saying thank you to exceptional, independent community leaders who share their passion, technical expertise, and real-world knowledge of Microsoft products with others. It is part of Microsoft’s commitment to supporting and enriching technical communities. Even before the rises of the Internet and social media, people have come together to willingly offer their ideas and best practices in technical communities.

My Journey So far...

My journey started on 11 July 2011, when I joined Mindfire Solutions. I was passionate for .NET Technologies during my Engineering days and fortunately I got a place in .NET Team after the training sessions.

I made many friends and some are indeed very special to me. They always encourage me for Community Activities and eventually I come to know about Code Project Community. Code Project is an awesome place to write Articles, Tips and Question Answer Activities. So, I went on answering the Questions first, then I gradually tried my hand on Articles and Tips. I got a very good response and votes from the viewers. The CodeProjectians always boost me for my work. I also started writing Blogs. Whenever I get time, I always look at the groups on Facebook and try to answer their queries. Twitter helped me to promote my writings all over the world. Tweeting good Programming resources is something I do regularly. My Reputation Manager had enough faith on me to give me the Moderation work for Dynamics CRM Team Blog.

The Teams I have worked for in my company have taught me many useful tricks to tackle problems on the fly. My previous .NET team was amazing, disciplined and always believe in fun filled workplace. My current Dynamics CRM Team has a bunch of Geeks, who are hard working and always deliver work on time. These champs taught me how to have patience in everything I do.

Then a special moment came !!! 1st January 2014, I got awarded as a Code Project MVP, which strengthened my chances for Microsoft MVP Award. My happiness knew no bounds. Then I worked harder than before.

Finally, on the April Fool's Day (6:57 PM IST), I got the mail from Biplab that I have been awarded. I was speechless !!!

Most common question now: How do you manage your time !!!

I am just crazy !!!

It makes you excited for the next question, when somebody appreciates the solution, which you have just answered. Try sometime, you will feel better for sure. Read below to know how mad I am.

  • Sleepless nights (not always, if I had replies on my answers or if somebody is waiting for my reply).
  • Working on weekends.
  • Answering questions while sitting at back seat of my friend's bike.
  • Immensely waiting for the network on my iPad to come at my native place, so that I can just answer one question.
  • Publish the code while working at office and in between the publish operation, answer one question.

There are many other situations, which can't be described here !!! :)

I would like to dedicate this to my...

Grand Father (Ganeswar Tripathy). His love and blessings always take me step by step towards success. All is for you, I miss you. :( :(

I would like to thank...

:: Biplab Paul (Community Program Manager, MVP Award Program – South Asia)- for his constant support and encouragement.
:: Siddharth Rout (Microsoft MVP) - This guys listened to all my stupid queries and answered them with patience. He is still busy doing the same for me.
:: Chris Maunder (Co-Founder, CodeProject) - for rebuilding the amazing forum time to time.
:: My CEO Mr. Chinmoy Panda, who is my idol and source of inspiration for me.
:: All Code Project MVPs and Staff.
:: Everybody who appreciated my Articles, Tips, Answers and Blogs.
:: My parents, family, friends, colleagues and relatives.
:: All my Managers, Tech Leads and Reputation Manager - These guys always appreciate my recognitions, which acts as a spur to contribute more.

What's Next?

As simple as that !!! Continue what I am doing and learn from my senior MVPs and my MVP lead. Involve myself in online/offline events. Add some more skills to my skill set.

Journey will continue... Bless me and wish me luck.
Thanks for reading, God bless you all !!!

Want to know more about me?

See my Brand New Microsoft MVP Profile here | Click here to know more About Me | Click here to Contact Me

Last, but not the least...

Get your Autograph Books ready. :)