Redirection from iframe in asp.net or javascript

In this tutorial we will learn how to perform redirection from IFrame in asp.net.
For example, I has a webpage that contains the form containing two textboxes and one asp:button. When click on button it redirects the user to another page but problem was that the next page was being opened inside the iframe rather than in parent window because the webpage that containing the form was also in iframe.

Solution 1
Here we using the server side onClick event of asp:button to redirecting user to another page and client side OnClientClick event to open new page in parent window. NewWindow() JavaScript code that we have written in the OnClientClick event of asp:button will take care that user must be redirected to next page within parent window rather than IFrame.

Code: (iFrame)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ashish Blog</title>
    <script type="text/javascript">
        function NewWindow() {
            document.forms[0].target = "_top";
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Ashish&amp;amp;#39;s Blog<br />
        UserName:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        Password:<asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="NewWindow();" onclick="Button1_Click"  />
    </div>
    </form>
</body>
</html>
 protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }

Solution 2:

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        ClientScript.RegisterStartupScript(this.GetType(), "redirect", "if(top!=self) {top.location.href = 'Default.aspx';}", true);  
    }

Note:- In case if this code is not working properly in IE9 then you have to give the absolute path of targeting webpage such as

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        ClientScript.RegisterStartupScript(this.GetType(), "redirect", "if(top!=self) {top.location.href = 'http://ashishblog.com/Default.aspx';}", true);  
    }

Currency Exchange Rate in webpage using C# ASP.NET

NOTE: GOOGLE turn off currency API but now you can https://www.google.com/finance/converter?a=1&from=AUD&to=INR

Some time ago I found the following Google API , which provides the currency conversion rates for free. Maybe you’ll find it useful.
In this article, I’ll explain how to get currency rate in ASP.Net using C#.

For example, 1 AUD = ? INR (1 Australian Dollar = ? Indian Rupee )
To get INR from 1 AUD, we need to call google API in following format: ( you can try by paste this url into your web browse)

http://www.google.com/ig/calculator?hl=en&q=1AUD%3D%3FINR
The number 1 before AUD is the amount of dollars or quantity.

Above Url returns a JSON object with the details.:

{lhs: "1 Australian dollar",rhs: "47.8167309 Indian rupees",error: "",icc: true}

As you can see the result is called rhs, but it combines the resulting value with the text “Indian rupees”. Now we will remove the string and store the result as a decimal.

We implement fuction called Convert with three parameter (amount, fromCurrency, toCurrency) which return Exchange rate in decimal.

Code:

public static decimal Convert(decimal amount, string fromCurrency, string toCurrency)
        {
            WebClient web = new WebClient();
 
            string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
 
            string response = web.DownloadString(url);
 
            Regex regex = new Regex("rhs: \\\\\\"(\\\\d*.\\\\d*)");
            Match match = regex.Match(response);
 
            decimal rate = System.Convert.ToDecimal(match.Groups[1].Value);
 
            return rate;
        }

Thanks

Search, Sort in gridview using C#.Net, Ajax and jQuery

In this article, I will show you how to search in Gridview by using SqlDataSource’s FilterParameters and Sort by using jQuery tablesorter plugin.

Step:1 Create Searchbox and Gridview
Create asp:textbox called txtSearch to search data.
then create a simple Gridview called Gridview1 with TemplateFields for the fields that you would like to search for. Here I created a Two TemplateField for my two search fields, First Name and Last Name. The other point of interest is that the Eval statement for these 2 fields is wrapped around a function that we’re going to write called HighlightText which is use to highlight search text.

 
<asp:ScriptManager ID="ScriptManager" runat="server" />
      Search: <asp:TextBox ID="txtSearch" runat="server" OnTextChanged="txtSearch_TextChanged"  />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" >
        <ContentTemplate>
            
            <div class="GridviewDiv">
           
                 <asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
                    AllowSorting="true" DataSourceID="dsGridview" Width="540px" PageSize="10" CssClass="yui">
                    <Columns>
                        <asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" ItemStyle-Width="40px"
                            ItemStyle-HorizontalAlign="Center" />
                        <asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
                            <ItemStyle Width="120px" HorizontalAlign="Left" />
                            <ItemTemplate>
                                <asp:Label ID="lblFirstname" Text='<%# HighlightText(Eval("FirstName").ToString()) %>' runat="server"
                                    CssClass="TextField" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
                            <ItemStyle Width="120px" HorizontalAlign="Left" />
                            <ItemTemplate>
                                <asp:Label ID="lblLastname" Text='<%# HighlightText(Eval("LastName").ToString()) %>' runat="server"
                                    CssClass="TextField" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department"
                            ItemStyle-Width="130px" />
                        <asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location"
                            ItemStyle-Width="130px" />
                    </Columns>
                </asp:GridView>
                </div>
        </ContentTemplate>
         <Triggers>
                <asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
            </Triggers>
    </asp:UpdatePanel>

Note that in above code, I put gridview1 into asp:updatePanel and set trigger to refresh UpdatePanel (Gridview1) when txtSearch value changed. Please do not put txtSearch into UpdatePanel.

Step 2: Create a datasource with a FilterExpression
In order to enable our search functionality, add a FilterExpression to the datasource. The FilterExpression that I’m using checks for the first name and last name against the txtSearch Text box.

 
 <asp:SqlDataSource ID="dsGridview" runat="server" ConnectionString="<%$ ConnectionStrings:TempConnectionString %>"
        SelectCommand="SELECT * FROM [Employees]" FilterExpression="firstname like '%{0}%' or lastname like '%{1}%'">
        <FilterParameters>
            <asp:ControlParameter Name="firstname" ControlID="txtSearch" PropertyName="Text" />
            <asp:ControlParameter Name="lastname" ControlID="txtSearch" PropertyName="Text" />
        </FilterParameters>
    </asp:SqlDataSource>

Step 3: CodeBehind C#
Basically every time we’re displaying the First and Last name data in our Gridview, we check to see if there is any search text, and if there is, use a regular expression to enclose the search string in a CSS span which turns the text yellow.

 
   string SearchString = "";
    protected void Page_Load(object sender, EventArgs e)
    {
txtSearch.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + txtSearch.ClientID.Replace("_", "$") + "\\',\\'\\')', 0);");
        if (!IsPostBack)
        {
            Gridview1.DataBind();
        }
    }
    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
         SearchString = txtSearch.Text;
    }
    public string HighlightText(string InputTxt)
    {
        string Search_Str = txtSearch.Text.ToString();
        // Setup the regular expression and add the Or operator.
        Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
        // Highlight keywords by calling the 
        //delegate each time a keyword is found.
        return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
        // Set the RegExp to null.
        RegExp = null;
    }
    public string ReplaceKeyWords(Match m)
    {
        return "<span class=highlight>" + m.Value + "</span>";
    }

Important: txtSearch_TextChanged event will not fire until you press enter. But to do a fast and easy search just typing in the textbox without havig to push any button or ‘enter’ to get the result back using AJAX updatepanel need to use Onkeyup event. just add this line to the Page_Load:

 
    txtSearch.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + txtSearch.ClientID.Replace("_", "$") + "\\',\\'\\')', 0);");

Step 4: Add the CSS class for highlighting

Step 5: Sorting Gridview
I’m using jQuery tableSorter plugin to sort gridvew. you can download from here.

 
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <script type="text/javascript" src="http://ashishblog.com/ash/source/jquery.tablesorter-2.0.3.js"></script>
  <link type="text/css" rel="stylesheet" href="http://ashishblog.com/ash/source/style.css" />
  <script type="text/javascript">
     jQuery(document).ready(function () {
         $("#Gridview1").tablesorter({ debug: false, widgets: ['zebra'], sortList: [[0, 0]] });
     });
</script>

Thanks.

jQuery Cookie Example

In this article I will show you how to set, Get, delete and edit cookie with jQuery.
First of all we need jQuery library (jquery-1.3.2.min.js) or any latest version and jQuery Cookie plugin (jquery.cookie.js) which you can download from here
Set Cookie

Get value of Cookie

delete Cookie:

Additionally, to set a timeout of a certain number of days (10 here) on the cookie:

Note: If the expires option is omitted, then the cookie becomes a session cookie, and is deleted when the browser exits.

To cover all the options:

Demo

Code:

Thanks.