Friday, 11 April 2014

Allow only One Decimal & Numerics Value in textbox in C# ASP.NET using JAVASCRIPT

Below is the function which will validate the text box value and will only allow one decimal and Numerics value in it.

Aspx Page:
<asp:TextBox ID="txtAmount" placeholder="Enter Amount Here" onkeypress="return onlyOneDotAndNumbers(this,event);" runat="server"></asp:TextBox>

Javascript Function:
 function onlyOneDotAndNumbers(txt, event) {
            var charCode = (event.which) ? event.which : event.keyCode
            if (charCode == 46) {
                if (txt.value.indexOf(".") < 0)
                    return true;
                else
                    return false;
            }

            if (txt.value.indexOf(".") > 0) {
                var txtlen = txt.value.length;
                var dotpos = txt.value.indexOf(".");
                if ((txtlen - dotpos) > 2)
                    return false;
            }

            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;

            return true;
        }

That’s it!!…..Happy Programming...

Sunday, 6 April 2014

How to Remove Unwanted Whitespace(s) between Words in C#

When dealing with user input (especially on web), we do not have control over some strange things. One common issue when user enter text, places too many spaces between words. A lot of times this is due to some copy and paste issue such as a user pasting text from a Microsoft Word document.

The common thought might be to add a bunch of replace methods to replace 2 spaces with 1, 3 spaces with 1, 4 spaces with 1, etc. Something like this :

enteredString = enteredString.Replace("  ", " ");
enteredString = enteredString.Replace("   ", " ");
enteredString = enteredString.Replace("    ", " ");


The main issue here is that you need to know in advance, for how many spaces you are looking to make this work correctly. For Example :-  In above case, if the string had more than 4 spaces, then things get disorderly. we could manually parse the string character by character, use peek and compare to find and remove spaces but there is actually an easier way to do this.


Using the method below, no matter how many spaces together in the string, this method will remove them and replace with a single space.

 public static string MoveOutExtraSpace(string enteredString)
 {
     enteredString = enteredString.Replace(" ", "()");
     enteredString = enteredString.Replace(")(", "");
     enteredString = enteredString.Replace("()", " ");
     enteredString = enteredString.Trim(); // for start and end space
     return enteredString;
 }

That’s it!!…..Happy Programming...

Sunday, 23 March 2014

Checkbox in Gridview header to select and deselect all rows using JavaScript

I am going to explain how to add checkbox in header template of gridview to select/deselect all rows using javascript or without any postback.
  <asp:TemplateField>
     <HeaderTemplate>
         <asp:CheckBox ID="chkSelectAllOrders" runat="server" onclick="ChkAllOrders(this);" />
     </HeaderTemplate>
     <ItemTemplate>
         <asp:CheckBox ID="ChkOrders" runat="server"></asp:CheckBox>
     </ItemTemplate>
 </asp:TemplateField>

Call this function in gridview header template, checkbox onclick event.
  <script type="text/javascript">
        function ChkAllOrders(Checkbox) {
            var gvHeaderChkbox = document.getElementById("<%=gvOrders.ClientID %>");
            for (i = 1; i < gvHeaderChkbox.rows.length; i++) {
                gvHeaderChkbox.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = Checkbox.checked;
            }
        }
    </script>
The above javascript function just gets the gridview id in its variable named 'gvHeaderChkbox'. After that a for loop is executed on gridview rows on its length basis. Please note that you must check your checkboxes on basis of cell position in that particular row. If you specify your checkboxes on 'xth' column than it means your cell value will be 'x-1'.


That’s it!!…..Happy Programming...

WHILE Loop With CONTINUE and BREAK Keywords in SQL SERVER

The break command terminates the loop, while continue causes a jump to the next iteration of the loop, skipping all the remaining code in that particular loop cycle.

Example of while Loop without break and continue:-

DECLARE @counter INT
SET @counter = 1
WHILE (@counter <=6)
BEGIN
PRINT @counter
SET @counter = @counter + 1
END
GO
Output:-  1  2  3  4  5  6


Example of while Loop with break:-

DECLARE @counter INT
SET @counter = 1
WHILE (@counter <=6)
BEGIN
PRINT @counter
SET @counter = @counter + 1
IF @counter = 3
BREAK;
END
GO
Output:-  1  2 (Because when counter reach on break command fire and terminate the loop, as i told you in definition)
 


Example of while Loop with break and continue:-
DECLARE @counter INT
SET @counter = 1
WHILE (@counter <=6)
BEGIN
PRINT @counter
SET @counter = @counter + 1
CONTINUE;
IF @counter = 5
BREAK;
END
GO
Output:-  1  2  3  4  5  6 (if you are thinking output should be 1 2 3 4, you are wrong because in the last example break would never executed. The reason behind that, every time continue  fired which forced to skip all remaining code for that particular cycle)


That’s it!!…..Happy Programming...

Tuesday, 4 March 2014

BeginUpdate() and EndUpdate() when populating ListView/TreeView in C# ASP.NET

Often a listview control in C# needs to be populated with large amount of data (bulky operations, for example, adding 1000 items). For every item added in the Listview, the control will redraw itself, thus greatly reduce the overall performance.

However, using the two methods BeginUpdate() and EndUpdate() while performing these bulk operations gives significant advantage. A call to BeginUpdate() can be made before adding/deleting/clearing items. This will stop any paint messages being sent or processed. Once the operation is done, the EndUpdate() can then be called.


I have logged the time taken of the above code (i.e. adding 1000 items in a ListView for each button click) with and without the BeginUpdate/EndUpdate method calls using a test application.
The use BeginUpdate() and EndUpdate populates the control with a constant duration and much better performance. Amazing, isn't it?

Here's a simple source code example for using this technique with a ListBox:

ListBox1.Items.BeginUpdate;

for i := 1 to 10000 do
    ListBox1.Items.Add('abcd');

ListBox1.Items.EndUpdate;
 
To give you an idea of the improvement, we timed the code above (your PC may be faster or slower):

without the BeginUpdate/EndUpdate lines: 4.3 seconds...
with BeginUpdate/EndUpdate: 0.1 seconds, that's 43 times faster!

 

That’s it!!…..Happy Programming...

How to Pass Encoded data in Query String in C# ASP.NET

Solution :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class encode
{
    public encode()
    {

    }
    public string base64Encode(string data)
    {
        try
        {
            byte[] encData = new byte[data.Length];
            encData = System.Text.Encoding.UTF8.GetBytes(data);
            string encodedData = Convert.ToBase64String(encData);
            return encodedData;
        }
        catch (Exception ex)
        {
            throw new Exception("Error in base64Encode" + ex.Message);
        }
    }
    public string base64Decode(string data)
    {
        try
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();

            byte[] todecode = Convert.FromBase64String(data);
            int charCount = utf8Decode.GetCharCount(todecode, 0, todecode.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode, 0, todecode.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }
        catch (Exception ex)
        {
            throw new Exception("Error in base64Decode" + ex.Message);
        }
    }
}
Just Create a class like this..Now call one of these method by just passing any string data, it will also return string data after encode/decode. Now you can pass this data in your query string just like any normal data.Now the question which was raised on our mind, What is base64 Encoding??

It's a textual encoding of binary data where the resultant text has nothing but letters, numbers and the symbols "+", "/" and "=". It's a convenient way to store/transmit binary data over media that is specifically used for textual data.


That’s it!!…..Happy Programming...