Monday, January 27, 2014

How to Set the ASP.NET Server Control Textbox value using JavaScript or Jquery

We can not access the server control by directly using it's id. You need to append and prepend the <%= and %> and also the ClientID. Because when rendering in browser the server control id will be change. If you are using JQuery to set the textbox value means you need to use # symbol. Check out the sample code clearly.
To get the server control value check my another post Click Here
HTML Code:
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>

JavaScript Code:
document.getElementById("<%= textbox1.ClientID %>").value = "values to set using JavaScript";

JQuery Code:
$("#<%= textbox1.ClientID %>").val("values to set using JQuery");

How to Get the ASP.NET Server Control Textbox value using JavaScript or Jquery

We can not access the server control value by directly using it's id. You need to append and prepend the <%= and %> and also the ClientID. Because when rendering in browser the server control id will be change. If you are using JQuery to get the textbox value means you need to use # symbol. Check out the sample code clearly.
To Set a value to server control check my another post Click Here
HTML Code:
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>

JavaScript Code:
var val1= document.getElementById("<%= textbox1.ClientID %>").value;

JQuery Code:
var val2= $("#<%= textbox1.ClientID %>").val();

Project Euler Solution using C#: Problem 7: 10001st Prime

Problem:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number?
My Solution:

static void Main(string[] args)
{
    bool isFound = false;
    bool isPrime = false;
    int limit = 10001;
    int count = 0;
    int val = 1;
    while (isFound == false)
    {
        if (val == 2)
        {
            count++;
        }
        else
        {
            for (int i = 2; i < val; i++)
            {
                if (val % i != 0 && val != i)
                {
                    isPrime = true;
                }
                else
                {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime)
            {
                count++;
                if (count == limit)
                {
                    Console.WriteLine("The" + limit + " th prime number is : " + val);
                }
            }
        }
        val++;
    }
    Console.ReadLine();
}
Note: You can simplifies the coding :)

Select only one checkbox at a time from the list of checkboxes using JQuery

Here i have created three checkbox named 1,2,3. When we click a checkbox, the name property of the current checkbox is retrived and checked using JQuery is() function and all other checkbox are unchecked using JQuery not() function.
HTML Code:
<input type="checkbox" name="fruits">1</input>
<input type="checkbox" name="fruits">2</input>
<input type="checkbox" name="fruits">3</input>

JQuery Code:
$(':checkbox').on('change',function(){
 var thiscb = $(this);
 var name = thiscb.prop('name');
 if(thiscb.is(':checked'))
 {
     $(':checkbox[name="'  + name + '"]').not($(this)).prop('checked',false);  
  }
});

Demo:

Click Here for Demo

Thursday, January 23, 2014

ASP.NET pie chart sample to set the chart area colors manually in code behind

Check out my previous sample to bind DataTable to Chart control Click Here. From the below code you can understand how to set the chart type, enable 3D chart, set the chart inclination angle, set the chart area colours manually in code behind and finally to format the lable displaying in the chart area. Here i have added the "%" symbol with label value that is displaying in the pie chart.
C# Code:
Chart1.Series["Series1"].Points.DataBind(chartData, "Key", "Value", string.Empty);
Chart1.Series["Series1"].ChartType = SeriesChartType.Pie;
Chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
Chart1.ChartAreas[0].Area3DStyle.Inclination = Convert.ToInt32(50);
foreach (Series charts in Chart1.Series)
{
     foreach (DataPoint point in charts.Points)
     {
             switch (point.AxisLabel)
             {
                      case "Name1": point.Color = Color.Green; break;
                      case "Name2": point.Color = Color.Blue; break;
                      case "Name3": point.Color = Color.Orange; break;
                      case "Name4": point.Color = Color.SandyBrown; break;
             }
             point.Label = string.Format("{0}%", point.YValues[0]);
             point.LegendText = point.AxisLabel;
     }
}

(Solved) Error: No http handler was found for request type 'GET' in ASP.NET Chart Control

Error:

No http handler was found for request type 'GET' in ASP.NET Chart Control
Solution:
  • Open your application web.config file.
  • Copy the below code and paste it inside the <configuration></configuration> tags.
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
    <remove name="ChartImageHandler"/>
    <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </handlers>
</system.webServer>
  • Hope it's fixed now

Project Euler Solution using C#: Problem 6: Sum Square Difference

Problem:

The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural  numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
My Solution:

static void Main(string[] args)
{
       int min = 1;
       int max = 100;
       int sumOfSq = 0;
       int temp = 0;
       int sqOfSum = 0;
       for (int i = min; i <= max; i++)
       {
           sumOfSq += (i * i);
       }
       for (int i = min; i <= max; i++)
       {
           temp += i;
       }
       sqOfSum = temp * temp;
       Console.WriteLine("Difference between the sum of the squares of the first one hundred"
       + "natural numbers and the square of the sum is :" + (sqOfSum - sumOfSq));
       Console.ReadLine();
}
Note: You can simplifies the coding :)

Wednesday, January 22, 2014

Show confirm alert before closing a page using JavaScript

Simple JavaScript code to display confirm alert before a page getting closed.
JavaScript Code:

    <script type="text/javascript">
        window.onbeforeunload = function (e) {
            return "Are you sure you want to close?";
        }
    </script>

Tuesday, January 21, 2014

Project Euler Solution using C#: Problem 5: Smallest Multiple

Problem:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
My Solution:

       static void Main(string[] args)
        {
            int num = 1;
            bool isDivisiblyByAll = false;
            bool isFound = false;
            while (isFound == false)
            {
                for (int i = 1; i <= 20; i++)
                {
                    if (num % i == 0)
                    {
                        isDivisiblyByAll = true;
                    }
                    else
                    {
                        isDivisiblyByAll = false;
                        break;
                    }
                }
                if (isDivisiblyByAll)
                {
                    isFound = true;
                    Console.WriteLine("Smallest positive number that is evenly divisible by all of the numbers from 1 to 20 is : " + num);
                }
                num++;
            }
            Console.ReadLine();
        }
Note: You can simplifies the coding :)

JavaScript Timer sample to hide a loading image after some seconds

A simple code to perform the timer functionality in Javascript. In the following example initially i have shown loading image using JQuery show() function. Then using the window.setInterval function i have set the Timer time to 5000 microseconds ie, 5 seconds. So the Hide function will execute after 5 seconds and the loading image will be hidden using the JQuery  hide() function. The JQuery show() and hide() function is equivalent to the CSS display block and none.
JavaScript Code:

<script type="text/javascript">
$('.img').show();
window.setInterval(Hide, 5000);
function Hide()
{
        $('.img').hide();

}
</script>

Monday, January 20, 2014

Catch Asynchronous postback from Updatepanel in ASP.NET to Show / Hide loading image

In some situation we need to display loading image when the Asynchronous post back in AP.NET Updatepanel. For that we need to catch the Asynchronous postback event. The below code will catch the postback and get the corresponding id of the control that makes the postback. So using the controlId you need to find the Updatepanel from which the postback occurred. So that we can show and hide the loading images in the specific Updatepanel. To find the Updatepanel here i used JQuery's closest function. Check the code.
Client Script:

<script type="text/javascript">
        $(document).ready(function() {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            if (prm != null) {
                prm.add_beginRequest(function(sender, e) {
                    var controlId = sender._postBackSettings.sourceElement.id;
                    var closestUpdatePanel= $('#' + controlId).closest(".UpdatepanelClass")
                });
            }
            prm.add_endRequest(function(sender, e) {
                var controlId = sender._postBackSettings.sourceElement.id;
                var closestUpdatePanel = $('#' + controlId).closest(".UpdatepanelClass")  
            });
        });
</script>

Thursday, January 16, 2014

Project Euler Solution using C#: Problem 4: Largest Palindrome Product

Problem:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.
My Solution: 


        static void Main(string[] args)         {             int min = 100;             int max = 999;             List<int> list = new List<int>();             int multiplied=0;>             for (int i = min; i < max; i++)             {                 for (int j = min; j < max; j++)                 {                     multiplied = i * j;                     string reversed = new string(multiplied.ToString().ToCharArray().Reverse().ToArray());                     if (reversed == multiplied.ToString())                     {                         list.Add(multiplied);                     }                 }             }             Console.WriteLine("the largest palindrome made from the product of two 3-digit numbers is : " + list.Max());             Console.ReadLine();         }
Note: You can simplifies the coding :)

Tuesday, January 14, 2014

(Solved) Error: The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

Error:

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
Solution:

You need to download and install the "2007 Office System Driver: Data Connectivity Components" to fix this error

Click Here to download from Microsoft


Note: Other version may not fix this error.