Friday, November 26, 2010

Disabling Browser Back Button after Logout

Recently in an application we developed there was a requirement to stop the browser back button after user logs out of the application.

The reason behind this was to stop the security risk of another user without proper permissions peeking into the earlier users screens. If you notice in many applications if the browser back is not properly handled then after the user is logged out you can re visit the site by just pressing the browser back button. This happens because the browser shows the cached page when the back is pressed. Even if you have server side code to check for the user they will not fire since the page will load from cache.

With the limited time I found a genius idea to handle this in the internet. What this javascript does is it will always try to put the user back to the last page in the history. For example, I am having a login page and a default page which I am taking a user after he logs in. You need to place the following javascript in the default page to make the above happen.





  1. <script type="text/javascript" language="JavaScript">
  2.     window.history.forward(1);
  3. </script>




Then once a user logs out from the system and if presses the back button of the browser, when the default page loads it will put the user again to login (history forward) page which is the login page. Ultimately user needs to login again to go back to the site.

Sunday, November 21, 2010

How to Set the Clock in Car Audio

After disconnecting the battery for a maintenance job, I had some clueless days while trying to reset the clock in a car audio system. Even though there should be a way to set the clock in audio systems it is bit difficult to find it without the manual of the system.

My in my scenario I found it after sometime, so thought to share it since it might help someone with the same problem.

Car audio system in which I had the issue was JVC KD-S5055.

To start the resetting you need to press and hold the “Select” button for about 5 seconds. Then a message similar to “Hour-h” will be shown in the display. Once this appears use the + and – buttons located on the left to set the hour value of the time.

Then to set the minute value you need to press the mode change buttons located on the right side. Once you press the mode change button while on the hour changing mode you will see a message similar to “Minute-m”. Then again you can use the + and – buttons to set the minutes portion of the time.

After successfully setting both hour portion and minute portion you can press the Select button again to save the changes made to he clock.

Additionally if you need the system to show the time when the device is switched on you can press the Display button located below the Select button. This will show the current time instead of the Radio/CD/Track information.

Hope this helps.

Wednesday, November 17, 2010

Sending the Same Letter to Different People with their Details

Today a friend of mine needed some help from me on sending the same letter to different people while addressing the letters differently. This can be easily achieved by using Word Mail Merge feature.

Since I am having Word 2010 installed in my machine this post will list the steps required in Word 2010.

1. To start the process type in your letter and click on Mailings on the Word 2010 ribbon.

2. Click on Start Mail Merge and select Letters.

3. Then you need to select the people you need to send the letter to. To do that you have three options Type List, Use Existing List or Select from Outlook contacts. In this post I will use the first option.

4. When you click Type new List… you will get a window in which you can create a list of users with their details as shown in the following screenshot. For simplicity I will only create 2 users.

When you are done creating the list of users click ok so you will be prompted with a save window. Save it for later use since you may need the list for future use.

5. Then in your letter go to the appropriate places you need to place the differencing information, for example I need to put the address of the receiver after the text The Manager. To do so place the cursor on the required location and press on Address Block icon on the ribbon.

From the Insert Address Block window you can customize the way the address is printed on the letter. For example if you do not want to print the company name of the recipient then you can remove the checkmark on the Insert company name field. Preview pane will show you a preview of the actual data you have in your contact list. For the simplicity I will use the default options.

When you press ok you will see something similar to the following appearing in your letter, which will be the placeholder for the address block.

Following similar method but using the Insert Merge Field icon I did add the title and the last name of the recipient into the body section of the letter as you see below.

6. Preview your work by clicking Preview Results icon, by clicking the navigation buttons on the preview results pane you can navigate through your contacts to see the actual letters that will be created. For example below screenshot shows the letter for Mr. Withana with the changes for him.

7. When you are satisfied you can finish the merge with three options, in my case I will use the first option again.

As the final output of the merge I got one new document with the 2 letters addressed to the recipients i had in my contact list as shown in the following screenshot.

Saturday, November 13, 2010

Configuring SQL Server Instance for Azure Development Storage

If you have not configured Azure Development Storage to use your SQL Server, then while running your application targeted for Azure you will see an error similar to the following.

“Windows Azure Tools: Failed to initialize Development Storage service. Unable to start Development Storage. Failed to start Development Storage: the SQL Server instance ‘localhost\SQLExpress’ could not be found. Please configure the SQL Server instance for Development Storage using the ‘DSInit’ utility in the Windows Azure SDK.”

To overcome this you need to run the DSInit command using Windows Azure SDK Command Prompt.

Step 1 – Start the Windows Azure SDK Command Prompt.

Step 2 – Type DSInit /sqlinstance:. on the prompt and press enter.

The dot (.) at the end denotes the local SQL Server instance running on your machine. DSInit command details are as follows.

Syntax:

DSInit [/sqlinstance:<SQL server instance>] [/forceCreate] [/user:<Windows account name>]

Description:

Initialize the development store for usage by

Reserving http ports for the blob, table and queue services for the current user, and

Creating the database needed by the blob and queue services

Options:

sqlinstance : the name of the SQL Server instance on the local machine that should

be used for Development Storage. The default is SQLExpress.

Use "." for unnamed instance.

forceCreate : recreate the database even if it already exists.

user : user for whom ports are to be reserved. By default it is the current user.

.

After doing the configurations it will display a success screen similar to the following.

Then when you run your Azure ready application the Azure Development Storage and Azure Development Fabric will get started and notify you on your system tray as shown below.

After a while your application will also start without complaining if it is Azure ready.

Tuesday, November 02, 2010

Saving Table Changes in SQL Server 2008 R2

Have you noticed that with the default settings of SQL Server 2008 R2 you cannot use the design view to edit and save table changes which requires table to be recreated. But if you used earlier SQL Server installations you should remember that this functionality was possible. When you try to save such a table you will see an error similar to the following in SQL Server 2008 R2.

But the good news is that we can enable this functionality by going to SQL Server options.

Click Tools –> Options and expand Designers node and select ‘Table and Database Designers’.

Then uncheck the option ‘Prevent saving changes that require table re-creation’ and press OK.

Now if you try to save the table changes SQL will do the alteration without any complains.

Sorting SharePoint Folder Contents

Recently I needed to sort the contents of a SharePoint folder, in which I used IComparer to get my task done. Following is the code I used. Hope it is helpful.

As you see below I am using the TimeCreated property of SPFile object to do the comparison, other than this you can use any other property of the SPFile object. For a list of available properties refer MSDN.





  1. // Comparer Class.
  2. public class SPFilesComparer : IComparer
  3. {
  4.     #region IComparer Members
  5.     public int Compare(object object1, object object2)
  6.     {
  7.         return new CaseInsensitiveComparer().Compare(((SPFile)object1).TimeCreated, ((SPFile)object2).TimeCreated);
  8.     }
  9.     #endregion
  10. }








  1. ArrayList fileList = new ArrayList(attachFiles);
  2. IComparer compFiles = new SPFilesComparer();
  3. // Do the sorting based on the SPFilesComparer.
  4. fileList.Sort(compFiles);
  5. foreach (SPFile attachFile in fileList)
  6. {
  7.     // Use the sorted list.
  8. }




Friday, October 22, 2010

Piano + Guitar = Harpejji

Are you interested in musical instruments? If so have you seen an instrument which combines the Piano and the Guitar? It is manufactured by a company named Marcodi and is named as Harpejji. The sounds from it is truly fascinating, experience the sounds for you self by visiting their site. For people who would like to buy it the pricing and ordering details are also there in the site.

Click this link to see the event of presenting Harpejji first time to the great musician A. R. Rahman.

Saturday, October 02, 2010

MaxLength property not Working in TextBox

If you are involved in coding using .Net sooner or later you will notice that when the TextMode of a TextBox is changed to MultiLine the MaxLength property will stop working. What this means is in the textbox users will be able to type as many character as they want.

When searching the web for a fix for this I found several ideas to solve this. Following is the code which I modified for my requirement. Hope this helps.

ASPX





  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head runat="server">
  3. <script type="text/javascript">
  4.     function RestrictLength(textBox) {
  5.         /* Get the Max Length attribute's value. */
  6.         var allowedLength = textBox.getAttribute('MaximumLength');
  7.         /* Check for the number of characters typed in by the user. */
  8.         if (textBox.value.length > allowedLength) {
  9.             /* If it is more than the allowed limit remove the additional text. */
  10.             textBox.value = textBox.value.substring(0, allowedLength);
  11.             /*  Show a message to user with the tooltip used for the textbox. */
  12.             alert("Maximum characters allowed for '" + textBox.title +"' is " + allowedLength + ".");
  13.         }
  14.     }
  15. </script>
  16.     <title></title>
  17. </head>
  18. <body>
  19.     <form id="form1" runat="server" style="vertical-align:top;">
  20.     <!-- I am binding my java script to the onkeyup event of the textbox. So each time a key
  21.     is pressed it will fire my javascript. -->
  22.     Address <asp:TextBox ID="TextBox1" runat="server" MaxLength="10"
  23.         onkeyup="RestrictLength(this);" Height="58px" TextMode="MultiLine"></asp:TextBox>
  24.     </form>
  25.     </body>
  26. </html>




 

ASPX.CS





  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     // Adding the attribute to the TextBox1.
  4.     // Note that this is different to the MaxLength property.
  5.     // Also this is not case sensitive.
  6.     TextBox1.Attributes.Add("maximumlength", "10");
  7.     // Adding a tooltip which is used in the message.
  8.     TextBox1.ToolTip = "User Address";
  9. }




The output will me something similar to the following.

Saturday, September 18, 2010

Repairing a Corrupted Database

When we are regularly using databases, sometimes those will get corrupted. This happened to one of my applications, it was a Windows Mobile application with SQL Server CE database. Since it is running in a mobile it is bit difficult for us to fix the database using the desktop machine. I used the following .Net Compact framework code to fix the corrupted database while the database is in the mobile.





  1. private void btnRepair_Click(object sender, EventArgs e)
  2. {
  3.     Cursor.Current = Cursors.WaitCursor;
  4.     Cursor.Show();
  5.     // txtDBPath will contain the path to the database.
  6.     engine = new SqlCeEngine(@"Data Source=" + txtDBPath.Text + ";Password=DBPassword");
  7.     try
  8.     {
  9.         if (!engine.Verify())
  10.         {
  11.             Cursor.Current = Cursors.Default;
  12.             Cursor.Hide();
  13.             DialogResult result = MessageBox.Show("Database is corrupted. Do you want to repair?", "My App", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
  14.             if (result == DialogResult.Yes)
  15.             {
  16.                 Cursor.Current = Cursors.WaitCursor;
  17.                 Cursor.Show();
  18.                 // You can also use RepairOption.DeleteCorruptedRows.
  19.                 engine.Repair(null, RepairOption.RecoverCorruptedRows);
  20.                 Cursor.Current = Cursors.Default;
  21.                 Cursor.Hide();
  22.                 MessageBox.Show("Database repaired successfully.", "My App");
  23.             }
  24.         }
  25.         else
  26.         {
  27.             Cursor.Current = Cursors.Default;
  28.             Cursor.Hide();
  29.             MessageBox.Show("Database is not corrupted.", "My App");
  30.         }
  31.     }
  32.     catch (Exception ex)
  33.     {
  34.         Cursor.Current = Cursors.Default;
  35.         Cursor.Hide();
  36.         MessageBox.Show(ex.Message, "Error!");
  37.     }
  38. }




Next time you get a corrupted SQL CE database try it out.

Friday, August 13, 2010

Cannot connect to YouTube using iPhone

Do you guys also get the ”Cannot connect to YouTube” error on your iPhone when using the provided YouTube application?

If yes follow the steps below to get it fixed.

1. Open Cydia from your spring board.

2. Press on the Manage tab in the bottom.

3. Press on Sources, then on Edit and press again on Add to add a new source.

4. Type the URL http://apt.iphonemodding.com and press on Add Source button.

5. Now find the iPhoneModding item and press on the triangle ‘>’.

6. Scroll down and find the “Push Fix” item and press on it.

7. Press Install to get Push Fix installed on your iPhone.

8. After pressing confirm on the confirmation screen the application will get installed on your iPhone.

 

9. After a complete restart you will be able to use YouTube application within your iPhone.

Monday, August 09, 2010

Comparing SharePoint 2010 vs 2007

It is some time since the SharePoint 2010 is released and now is a good time for you to migrate to the new improved version of it. When searching the net I found some good sites which compares the 2 versions.

Read through the following sites if you are interested.

http://www.rharbridge.com/?page_id=103

http://www.khamis.net/blog/Lists/Posts/Post.aspx?ID=4

Sunday, August 08, 2010

Installing and Uninstalling Internet Explorer 8

Since Internet Explorer (IE) 8 is a built-in feature of Windows Server 2008 R2 there is no way to install or uninstall it using the user interfaces. Instead you need to run the following commands in a command prompt window which has administrative privileges.

If you are only having IE in your machine as an internet browser be sure to install another internet browser before uninstalling IE, otherwise you will not be able to browse internet.

  1. Click the start button and type Cmd in the search box.
  2. Right click on the Cmd icon and click on Run as Administrator.
  3. Choose the appropriate command from below for your need and copy it.

To Install -

dism /online /Enable-Feature /FeatureName:Internet-Explorer-Optional-amd64

To Uninstall -

dism /online /Disable-Feature /FeatureName:Internet-Explorer-Optional-amd64

or

FORFILES /P %WINDIR%\servicing\Packages /M Microsoft-Windows-InternetExplorer-8*.mum /c "cmd /c echo Uninstalling package @fname && start /w pkgmgr /up:@fname /norestart"

  1. Paste the command into the command prompt windows you just opened by right clicking and clicking on Paste.
  2. Press enter to run the command, when the command is successful you need to restart your machine to complete the action.

Tuesday, August 03, 2010

Rounding a value Down

If you did work with .Net Math classes you may have noted that you can quite easily round value upwards. But what about rounding values down?

For example if you tried to round the value 1.23501 into 2 decimal places using the Round method provided by the Math class as below, the result you will get is 1.24. Meaning .Net had rounded the value up.





  1. double dbl = Math.Round(1.23501, 2);




If the value is rounded down it should be 1.23, but in .Net I couldn’t find an easy way to get this done. So I did create a small code to get it done. It is very simple only a method with one statement as shown below.





  1. double RoundDown(double Number, int Digits)
  2. {
  3.     try
  4.     {
  5.         return Math.Truncate(Number) +
  6.             (Math.Floor(Math.Round((Number % 1), Digits) * Math.Pow(10, (Math.Round((Number % 1), Digits).ToString().Length - 3)))) *
  7.             (1 / Math.Pow(10, Math.Round((Number % 1), Digits).ToString().Length - 3));
  8.     }
  9.     catch (Exception)
  10.     {
  11.         MessageBox.Show("Error ! Please check values.");
  12.         return 0.0;
  13.     }
  14. }




Ohh, I think this is complicated right? Please find a bit of self explanatory code below.





  1. double RoundDownExplained(double Number, int Digits)
  2. {
  3.     try
  4.     {
  5.         // Get the whole number from the double value.
  6.         // For example we'll take Number = 788.34567 and Digits = 3.
  7.         // WholeNumberPart = 788.
  8.         double WholeNumberPart = Math.Truncate(Number);
  9.         // Getting the decimal part from the doouble value.
  10.         // DecimalNumberPart = 0.3457.
  11.         double DecimalNumberPart = Math.Round((Number % 1), Digits);
  12.         // Finding the number of decimal places so we can multiply by 10 to make it suitable for Floor().
  13.         // MultiplicationValue = 3.
  14.         int MultiplicationValue = Math.Round((Number % 1), Digits).ToString().Length - 3;
  15.         // Create the double value to round down.
  16.         // RoundedDownValue = 345.
  17.         double RoundedDownValue = Math.Floor(DecimalNumberPart * Math.Pow(10, MultiplicationValue));
  18.         // Finding the value to devide the result to make it decimal again.      
  19.         // DivisionValue = 0.001.            
  20.         double DivisionValue = 1 / Math.Pow(10, MultiplicationValue);
  21.         // Creating the decimal part with rounded down value.
  22.         // RoundedDownValue_Float = 0.345.
  23.         double RoundedDownValue_Float = RoundedDownValue * DivisionValue;
  24.         // Creating the full rounded down value.
  25.         // return = 788.345.
  26.         return WholeNumberPart + RoundedDownValue_Float;
  27.     }
  28.     catch (Exception)
  29.     {
  30.         MessageBox.Show("Error ! Please check values.");
  31.         return 0.0;
  32.     }
  33. }




The complete code of the application I created is below with a screenshot of the application running. Hope this helps to you.





  1. using System;
  2. using System.Text;
  3. using System.Windows.Forms;
  4. namespace WindowsFormsApplication1
  5. {
  6.     public partial class Form1 : Form
  7.     {
  8.         public Form1()
  9.         {
  10.             InitializeComponent();
  11.         }
  12.         double RoundDown(double Number, int Digits)
  13.         {
  14.             try
  15.             {
  16.                 return Math.Truncate(Number) +
  17.                     (Math.Floor(Math.Round((Number % 1), Digits) * Math.Pow(10, (Math.Round((Number % 1), Digits).ToString().Length - 3)))) *
  18.                     (1 / Math.Pow(10, Math.Round((Number % 1), Digits).ToString().Length - 3));
  19.             }
  20.             catch (Exception)
  21.             {
  22.                 MessageBox.Show("Error ! Please check values.");
  23.                 return 0.0;
  24.             }
  25.         }
  26.         double RoundDownExplained(double Number, int Digits)
  27.         {
  28.             try
  29.             {
  30.                 // Get the whole number from the double value.
  31.                 // For example we'll take Number = 788.34567 and Digits = 3.
  32.                 // WholeNumberPart = 788.
  33.                 double WholeNumberPart = Math.Truncate(Number);
  34.                 // Getting the decimal part from the doouble value.
  35.                 // DecimalNumberPart = 0.3457.
  36.                 double DecimalNumberPart = Math.Round((Number % 1), Digits);
  37.                 // Finding the number of decimal places so we can multiply by 10 to make it suitable for Floor().
  38.                 // MultiplicationValue = 3.
  39.                 int MultiplicationValue = Math.Round((Number % 1), Digits).ToString().Length - 3;
  40.                 // Create the double value to round down.
  41.                 // RoundedDownValue = 345.
  42.                 double RoundedDownValue = Math.Floor(DecimalNumberPart * Math.Pow(10, MultiplicationValue));
  43.                 // Finding the value to devide the result to make it decimal again.      
  44.                 // DivisionValue = 0.001.            
  45.                 double DivisionValue = 1 / Math.Pow(10, MultiplicationValue);
  46.                 // Creating the decimal part with rounded down value.
  47.                 // RoundedDownValue_Float = 0.345.
  48.                 double RoundedDownValue_Float = RoundedDownValue * DivisionValue;
  49.                 // Creating the full rounded down value.
  50.                 // return = 788.345.
  51.                 return WholeNumberPart + RoundedDownValue_Float;
  52.             }
  53.             catch (Exception)
  54.             {
  55.                 MessageBox.Show("Error ! Please check values.");
  56.                 return 0.0;
  57.             }
  58.         }
  59.         private void button1_Click(object sender, EventArgs e)
  60.         {
  61.             try
  62.             {
  63.                 label1.Text = RoundDown(double.Parse(textBox1.Text), int.Parse(textBox2.Text) + 1).ToString();
  64.             }
  65.             catch (Exception)
  66.             {
  67.                 MessageBox.Show("Error ! Please check values.");
  68.             }
  69.         }
  70.         private void button2_Click(object sender, EventArgs e)
  71.         {
  72.             try
  73.             {
  74.                 label2.Text = RoundDownExplained(double.Parse(textBox1.Text), int.Parse(textBox2.Text) + 1).ToString();
  75.             }
  76.             catch (Exception)
  77.             {
  78.                 MessageBox.Show("Error ! Please check values.");
  79.             }
  80.         }
  81.     }
  82. }




Saturday, July 31, 2010

Error Accessing Path

Today is a day full of errors, when I fixed one error another error came while trying to run my hosted application. This time it was “Access to the path 'C:\inetpub\wwwroot\……’ is denied.

Full error is as follows,

Access to the path 'C:\inetpub\wwwroot\Mining2 Setup\Images\temp\tempImage.png' is denied.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Access to the path 'C:\inetpub\wwwroot\Mining2 Setup\Images\temp\tempImage.png' is denied.

image_thumb[2]

The issue here was generated by a code written in my application which tries to access an image named tempImage.png in the said folder (Images\temp).

The reason for this is when you install IIS 7 the account used by the application pool (IIS_IUSRS) is not given access to the folder Images\temp. Since it is created by the application I just installed.

To sort out the issue give write permission to the folder Images\temp for the account IIS_IUSRS using the security tab in the folder properties page.

image_thumb[4]

Friday, July 30, 2010

Error when Installing MSI

Recently when trying to install a setup I made for a project on a new server having Windows Server 2008 R2 I continuously encountered an error as of below.

“The installer was interrupted before “Application” could be installed. You need to restart the installer to try again.”

image_thumb[2]

The server had IIS 7, .Net Framework 3.5 and 4 installed. After putting in some time onto this I found out that this is because the II6 Management Compatibility services was not installed for the Web Server role.

To fix it simply open the Server Manager and open up Web Server role and click on Add Role Services.

image Then select IIS 6 Management Compatibility node and all the child nodes below in under the Management Tools parent node and press next.

image When the installation is complete the setup will work as desired.

image_thumb[4]

Friday, July 23, 2010

Changing the Control Style at Runtime using the ASPX

Recently I changed the style of some controls in my ASPX page at runtime based on the values set on another control in my page. For example the color of the table is changed based on the radio button that was selected and the color of the button is changed according to the text that was typed in the textbox. Hope this is helpful.





  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head runat="server">
  3.     <title>Changing the Control Style</title>
  4.      <style type="text/css">
  5.         .Style1
  6.         {
  7.             background-color: Red;
  8.         }
  9.         .Style2
  10.         {
  11.             background-color: Blue;
  12.         }
  13.     </style>
  14. </head>
  15. <body>
  16.     <form id="form1" runat="server">
  17.         <asp:RadioButton ID="RadioButton1" runat="server" Text="Red" GroupName="1" Checked="True" AutoPostBack="True" />
  18.         <asp:RadioButton ID="RadioButton2" runat="server" Text="Blue" GroupName="1" AutoPostBack="True" />
  19.         <!-- Styling the table based on the radio button selection. -->
  20.         <table class="<% if(RadioButton1.Checked) { %> Style1 <% } else { %> Style2 <% } %>">
  21.             <tr>
  22.                 <td> &nbsp; See the change... </td>
  23.             </tr>
  24.             <tr>
  25.                 <td> &nbsp; </td>
  26.             </tr>
  27.         </table>
  28.         <asp:TextBox ID="TextBox1" runat="server" MaxLength="3"></asp:TextBox>
  29.         <!-- Styling the button based on the textbox value. -->
  30.         <input id="Button1" type="submit" value="button"
  31.                class="<% if(TextBox1.Text=="") { %> Style1 <% } else { %> Style2 <% } %>" />
  32.     </form>
  33. </body>
  34. </html>




Output looks as below.

Tuesday, July 20, 2010

Cure for HIV/AIDS

Even though very little publicity was given a great medical finding was done by an American Doctor working in Berlin to find a cure for HIV/AIDS or Human Immunodeficiency Virus / Acquired Immune Deficiency Syndrome.

As per the articles a stem cell transplant from a donor who had a gene mutation known as “CCR-5 Delta- 32” cured a patient with HIV infection with no traces of HIV after two years of the transplant.

At the moment a transplant is much riskier thing to do since it involves of destroying and rebuilding the patients’ immune system. But this case of success will open up new ways to think and will help finding more safe and solid cures for HIV/AIDS in the near future.

Read more,

http://edition.cnn.com/2009/HEALTH/02/11/health.hiv.stemcell/

http://www.baldwincountynow.com/articles/2009/05/28/local_news/doc4a1d63cb68531598814432.txt

Thursday, July 15, 2010

Firing TreeView TreeNodeCheckChanged Event

Normally in ASP.Net TreeView you can enable it to show checkboxes in its node levels. So if you need to do any actions when a node is checked or unchecked you need to use the TreeNodeCheckChanged event. But the problem is TreeNodeCheckChanged event will not fire when a checkbox is clicked. The cause for this is because the TreeNode class which represents a node in the TreeView will not add onClick event on the checkbox.

But if you carefully check it the event is getting fired at the next page postback. Since I needed to do some actions when the checkbox statuses are changed I made the page post back when a checkbox is checked or unchecked by the following java script. What it does is simply it will check the element which caused the event is a checkbox and do a postback of the page.





  1. <script type="text/javascript">
  2.     function TreeViewCheckBoxClicked(Check_Event) {
  3.         var objElement;
  4.         try {
  5.             // Get the element which fired the event.
  6.             objElement = window.event.srcElement;
  7.         }
  8.         catch (Error) {
  9.             //srcElement is failing, objElement is null.
  10.         }
  11.         if (objElement != null) {
  12.             // If the element is a checkbox do postback.
  13.             if (objElement.tagName == "INPUT" && objElement.type == "checkbox") {
  14.                 __doPostBack("", "");
  15.             }
  16.         }
  17.         else {
  18.             //    If the srcElement is failing due to browser incompatibility determine
  19.             // whether the element is and HTML input element and do postback.
  20.             if (Check_Event != null) {
  21.                 if (Check_Event.target.toString() == "[object HTMLInputElement]") {
  22.                     __doPostBack("", "");
  23.                 }
  24.             }
  25.         }
  26.     }
  27. </script>




To make this work you need to bind the onClick event with the javascript shown above as shown below.





  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     // Adding the onClick script to the TreeView.
  4.     TreeView1.Attributes.Add("onClick", "TreeViewCheckBoxClicked(event)");
  5. }




Even though I have done this in Page Load this can be done in other places of code as well, for example if you are adding the TreeView by code you can use this right before adding it to the page.

The above will make the page post back when ever a checkbox in the TreeView is clicked, but nothing special will happen. You need to implement the code for TreeNodeCheckChanged event to get some task done out of it, for example I am using the following code to check or uncheck the child nodes depending on the action done for the parent node.





  1. protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
  2. {
  3.     // Loop through all the child nodes and change the checked status as required.
  4.     foreach (TreeNode tn in e.Node.ChildNodes)
  5.     {
  6.         if (e.Node.Checked)
  7.             tn.Checked = true;
  8.         else
  9.             tn.Checked = false;
  10.     }
  11. }




Tuesday, July 13, 2010

Changing GridView Column Headers

If you are wondering a way to change the column header appearing in the .Net GridView control in run time then this post will help you to get it done.

For example think that you need to change the normal grid headers shown in Screen A into something like shown in Screen B.

Screen A

Screen B

I have removed few columns from the grid header and then I did add few customized column headers. The added “Edit” column and “Id” column are spanning to 2 rows, the “Temp Columns” column is spanning to 2 columns.

I think the code is self explanatory. This way you will be able to create complex gridview headers.





  1. protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
  2. {
  3.      if (e.Row.RowType == DataControlRowType.Header)
  4.      {
  5.          // Remving the first two colummn headers.
  6.          e.Row.Cells.RemoveAt(0);
  7.          e.Row.Cells.RemoveAt(0);
  8.          // Creating the gridview row object.
  9.          GridViewRow headerGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Selected);
  10.          headerGridRow.ID = "hdrGridRow";
  11.          TableCell HeaderCell;
  12.          // Creating and adding the first header cell.
  13.          HeaderCell = new TableCell();
  14.          HeaderCell.Text = "Edit";
  15.          HeaderCell.ID = "cellEdit";
  16.          HeaderCell.Font.Bold = false;
  17.          HeaderCell.HorizontalAlign = HorizontalAlign.Center;
  18.          HeaderCell.RowSpan = 2; // Spans across 2 rows.
  19.          HeaderCell.ColumnSpan = 1;
  20.          HeaderCell.BackColor = System.Drawing.Color.LightGray;
  21.          HeaderCell.BorderColor = System.Drawing.Color.White;
  22.          HeaderCell.ForeColor = System.Drawing.Color.Red;
  23.          headerGridRow.Cells.Add(HeaderCell);
  24.          // Creating and adding the second header cell.
  25.          HeaderCell = new TableCell();
  26.          HeaderCell.Text = "Id";
  27.          HeaderCell.ID = "cellId";
  28.          HeaderCell.Font.Bold = false;
  29.          HeaderCell.HorizontalAlign = HorizontalAlign.Center;
  30.          HeaderCell.RowSpan = 2;
  31.          HeaderCell.ColumnSpan = 1;
  32.          HeaderCell.BackColor = System.Drawing.Color.LightGray;
  33.          HeaderCell.BorderColor = System.Drawing.Color.White;
  34.          HeaderCell.ForeColor = System.Drawing.Color.Red;
  35.          headerGridRow.Cells.Add(HeaderCell);
  36.          // Creating and adding the third header cell.
  37.          HeaderCell = new TableCell();
  38.          HeaderCell.Text = "Temp Columns";
  39.          HeaderCell.ID = "cellTempColumns";
  40.          HeaderCell.Font.Bold = false;
  41.          HeaderCell.HorizontalAlign = HorizontalAlign.Center;
  42.          HeaderCell.RowSpan = 1;
  43.          HeaderCell.ColumnSpan = 2; // Spans across 2 columns.
  44.          HeaderCell.BackColor = System.Drawing.Color.LightGray;
  45.          HeaderCell.BorderColor = System.Drawing.Color.White;
  46.          HeaderCell.ForeColor = System.Drawing.Color.Red;
  47.          headerGridRow.Cells.Add(HeaderCell);
  48.          // Adding the header row to the gridview.
  49.          GridView1.Controls[0].Controls.AddAt(0, headerGridRow);
  50.      }
  51. }