Monday, April 20, 2009

How To Read xml using JQuery

In this post i will show how to read xml using JQuery
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!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></title>

   <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

   <script type="text/javascript">

       $(document).ready(function() {
           $.get('Data.xml', function(d) {
               var data = "";
               var startTag = "<table border='1' id='mainTable'><tbody><tr><td style=\"width: 120px\">Name</td><td style=\"width: 120px\">Link</td></tr>";
               var endTag = "</tbody></table>";
               $(d).find('url').each(function() {
                   var $url = $(this);
                   var link = $url.find('link').text();
                   var name = $url.find('name').text();
                   data += '<tr><td>' + name + '</td>';
                   data += '<td>' + link + '</td></tr>';
               })
               $("#content").html(startTag + data + endTag);
               ;
           });

       });
   </script>

</head>
<body>
   <div id="content">
   </div>
</body>
</html>
Data.xml
<?xml version="1.0" encoding="utf-8" ?>
<Urls>
 <url>
   <name>google</name>
   <link>
     www.google.com
   </link>
 </url>
 <url>
   <name>aspdotnetcodebook</name>
   <link>http://aspdotnetcodebook.blogspot.com</link>
 </url>
</Urls>

Sunday, April 19, 2009

jQuery Ajax call and result XML parsing in asp.net

In this post i will show how to use Jquery in asp.net
  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual C# Projects
  4. Add a new xml file and copy the following xml.
labels.xml
<?xml version="1.0" encoding="utf-8"?>
<labels>
<label id="1">
<name>Test</name>
<address>
  <street>street1</street>
  <city>City1</city>
  <province>ID</province>
</address>
</label>
<label id='2'>
<name>Name2</name>
<address>
  <street>Street2</street>
  <city>City2</city>
  <province>CT</province>
</address>
</label>

</labels>

5. Add a reference to the jQuery script 6.Copy below code in aspx page.
<%@ 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></title>

  <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

  <script type="text/javascript">
   $(function() {
       $('#update-target a').click(function() {
           $.ajax({
               type: "GET",
               url: "labels.xml",
               dataType: "xml",
               success: function(xml) {
                   $(xml).find('label').each(function(){
                       var id_text = $(this).attr('id')
                       var name_text = $(this).find('name').text()

                       $('<li></li>')
                           .html(name_text + ' (' + id_text + ')')
                           .appendTo('#update-target ol');
                   }); //close each(
               }
           }); //close $.ajax(
       }); //close click(
   }); //close $(
  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <p>
          <div id='update-target'>
              <a href="#">Click here to load addresses</a>
              <ol>
              </ol>
          </div>
      </p>
  </div>
  </form>
</body>
</html>

Saturday, April 18, 2009

How To Include Content of One Page To another Page

In this post i will show how to include the content of one page inside another using Regular expression .
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblHtml" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      lblHtml.Text= ParseHtml();

    }
    private static string ParseHtml()
    {
        StreamReader sr;
        string html;
        sr = File.OpenText(HttpContext.Current.Server.MapPath("Default.aspx"));
        html = sr.ReadToEnd();
        sr.Close();

        Regex
            start = new Regex(@"[\s\S]*<body[^<]*>", RegexOptions.IgnoreCase);
        html = start.Replace(html, "");
        Regex end = new Regex(@"</body[\s\S]*", RegexOptions.IgnoreCase);
        html = end.Replace(html, "");
        return html;
    }
}

Wednesday, April 8, 2009

How To Select Value of gridview row using javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestDDL.aspx.cs" Inherits="TestDDL" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManger1" runat="server">
    </asp:ScriptManager>
    <div>
    </div>
    <style>
        .invisibleColumn
        {
            display: none;
            width: 0px;
        }
        body
        {
            font-family: Arial;
            font-size: 12px;
        }
    </style>

    <script type="text/javascript">
        function getValue(obj) {

            document.getElementById('<%=txtFriend.ClientID %>').value = obj;
        }
    </script>

    <asp:UpdatePanel ID="Update1" runat="server">
        <ContentTemplate>
            <cc1:DropDownExtender ID="DropDownExtender1" DropDownControlID="FriendGridView" TargetControlID="txtFriend"
                runat="server">
            </cc1:DropDownExtender>
            <asp:TextBox ID="txtFriend" runat="server" Width="200px"></asp:TextBox>
            <asp:GridView ID="FriendGridView" runat="server" Width="200px" AutoGenerateColumns="false"
                OnRowDataBound="FriendGridView_RowDataBound" OnSelectedIndexChanged="FriendGridView_SelectedIndexChanged">
                <RowStyle BackColor="#DDDDDD" />
                <Columns>
                    <asp:BoundField DataField="ID" HeaderStyle-CssClass="invisibleColumn" ItemStyle-CssClass="invisibleColumn" />
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:BoundField DataField="Description" HeaderText="Description" />
                </Columns>
                <HeaderStyle BackColor="Blue" ForeColor="White" />
                <AlternatingRowStyle BackColor="#EEEEEE" />
                <SelectedRowStyle BackColor="#999999" />
            </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class TestDDL : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FriendGridView.DataSource = GetFriends();
            FriendGridView.DataBind();
        }

    }
    protected void FriendGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // The value that we want is in column #9...
            string valueText = e.Row.Cells[1].Text;

            string clickHandler = string.Format("alert('Value in column #9 is {0}')", valueText);
            e.Row.Attributes.Add("onclick", "getValue('" + valueText + "')");
        }
    }
    public List<Friend> GetFriends()
    {

        List<Friend> users = new List<Friend>();
        users.Add(new Friend("Xyz", "Coder"));
        users.Add(new Friend("Abc", "Writer"));
        users.Add(new Friend("Charles", "Poet"));
        return users;


    }
    protected void FriendGridView_SelectedIndexChanged(object sender, EventArgs e)
    {
        // assign firstname
        if (FriendGridView.SelectedRow != null)
            txtFriend.Text = Server.HtmlDecode(
              FriendGridView.SelectedRow.Cells[1].Text);
        else
            txtFriend.Text = "";

    }
}
public class Friend
{

    public Friend(string name, string description)
    {

        _name = name;

        _description = description;

        _id = Guid.NewGuid().ToString();

    }



    private string _id;
    public string Id
    {

        get { return _id; }

        set { _id = value; }

    }

    private string _name;
    public string Name
    {

        get { return _name; }

        set { _name = value; }

    }
    private string _description;
    public string Description
    {

        get { return _description; }

        set { _description = value; }

    }
}

Tuesday, April 7, 2009

how to convert web page to pdf

In this post i will show how to convert web page to pdf using iTextSharp.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Pdf.aspx.cs" Inherits="Pdf" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:PlaceHolder ID="PlaceholderPdf" runat="server"></asp:PlaceHolder>
    <div>
        <table border="1">
            <tr>
                <td colspan="2">
                    aspdotnetcodebook
                </td>
            </tr>
            <tr>
                <td>
                    cell1
                </td>
                <td>
                    cell2
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblLabel" runat="server" Text="Label Test"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using System.Xml;
using iTextSharp.text.html.simpleparser;
public partial class Pdf : System.Web.UI.Page
{
    protected override void Render(HtmlTextWriter writer)
    {
        MemoryStream mem = new MemoryStream();
        StreamWriter twr = new StreamWriter(mem);
        HtmlTextWriter myWriter = new HtmlTextWriter(twr);
        base.Render(myWriter);
        myWriter.Flush();
        myWriter.Dispose();
        StreamReader strmRdr = new StreamReader(mem);
        strmRdr.BaseStream.Position = 0;
        string pageContent = strmRdr.ReadToEnd();
        strmRdr.Dispose();
        mem.Dispose();
        writer.Write(pageContent);
        CreatePDFDocument(pageContent);


    }
    public  void CreatePDFDocument(string strHtml)
    {

        string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
        // step 1: creation of a document-object
        Document document = new Document();
        // step 2:
        // we create a writer that listens to the document
        PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
        StringReader se = new StringReader(strHtml);
        HTMLWorker obj = new HTMLWorker(document);
        document.Open();
        obj.Parse(se);
        document.Close();
        ShowPdf(strFileName);
     
   
     
    }
    public void ShowPdf(string strFileName)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
        Response.ContentType = "application/pdf";
        Response.WriteFile(strFileName);
        Response.Flush();
        Response.Clear();
    }
}

Saturday, April 4, 2009

ASP.NET and Ajax - using XmlHttpRequest

In this post i will show how to use XmlHttpRequest object in asp.net.Here's an example that fetches the Product details by categoryid.Create a new web application and add following code on Default.aspx page( I have used Ajax.aspx). Ajax.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ajax.aspx.cs" Inherits="Ajax" %>

<!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></title>

  <script type="text/javascript">
      function GetXmlHttpObject(handler) {
          var objXmlHttp = null
          if (navigator.userAgent.indexOf("Opera") >= 0) {
              alert("This example doesn't work in Opera")
              return
          }
          if (navigator.userAgent.indexOf("MSIE") >= 0) {
              var strName = "Msxml2.XMLHTTP"
              if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {
                  strName = "Microsoft.XMLHTTP"
              }
              try {
                  objXmlHttp = new ActiveXObject(strName)
                  objXmlHttp.onreadystatechange = handler
                  return objXmlHttp
              }
              catch (e) {
                  alert("Error. Scripting for ActiveX might be disabled")
                  return
              }
          }
          if (navigator.userAgent.indexOf("Mozilla") >= 0) {
              objXmlHttp = new XMLHttpRequest()
              objXmlHttp.onload = handler
              objXmlHttp.onerror = handler
              return objXmlHttp
          }
      }

      function GetProduct(id) {
          var url = "Details.aspx?CatId=" + id;
          xmlHttp = GetXmlHttpObject(stateChanged);
          xmlHttp.open("GET", url, true);
          xmlHttp.send(null);
      }


      function stateChanged() {
          if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
              document.getElementById('ProductDetails').innerHTML = xmlHttp.responseText;
          }
      }

  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <div>
          <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
              DataTextField="CategoryName" DataValueField="CategoryID">
          </asp:DropDownList>
      </div>
      <div id="ProductDetails">
      </div>
  </div>
  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:northwindConnectionString %>"
      SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]"></asp:SqlDataSource>
  </form>
</body>
</html>



Ajax.aspx.cs



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

public partial class Ajax : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
      if (!Page.IsPostBack)
      {
          DropDownList1.DataBind();
          DropDownList1.Items.Insert(0, "");
      }
      DropDownList1.Attributes["onChange"] = "GetProduct(this.value);";
      HttpResponse myHttpResponse = Response;
      HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);
      DropDownList1.Attributes.AddAttributes(myHtmlTextWriter);


  }
}
And finally create Details.aspx page and remove everything from .aspx page except the first line. write down following code on Page_Load event of details.aspx page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data.SqlClient;

public partial class Details : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       Response.Clear();
       StringBuilder sb = new StringBuilder();
       sb.Append("<br />");
       string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["northwindConnectionString"].ConnectionString;
       string query = "SELECT * FROM Products WHERE CategoryId = @CustId";
       SqlConnection conn = new SqlConnection(connstr);
       SqlCommand cmd = new SqlCommand(query, conn);
       cmd.Parameters.AddWithValue("@CustId", Request.QueryString["CatId"]);
       conn.Open();
       SqlDataReader dr = cmd.ExecuteReader();
       while (dr.Read())
       {
           sb.Append(dr[1].ToString() + "<br />");
           sb.Append(dr[2].ToString() + "<br />");
           sb.Append(dr[3].ToString() + "<br />");
           sb.Append(dr[4].ToString() + "<br />");
           sb.Append(dr[5].ToString() + "<br />");
           sb.Append(dr[6].ToString() + "<br />");
       }
       dr.Close();
       dr.Dispose();
       conn.Close();
       conn.Dispose();
       Response.Write(sb.ToString());
       Response.End();

   }
}

How To Move Selected Record From One GridView to another

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MoveRecord.aspx.cs" Inherits="MoveRecord" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gridView1" runat="server">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkSelect" runat="server" />
                        <asp:HiddenField ID="hdValue" runat="server" Value='<%#Eval("ID") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    <div>
        <asp:Button ID="btnMove" runat="server" Text="Move" OnClick="btnMove_Click" />
    </div>
    <div>
        <asp:GridView ID="gridView2" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class MoveRecord : System.Web.UI.Page
{
    const string key = "MyDataSource";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }

    }
    private void BindGridView()
    {
        if (Session[key] == null)
        {
            gridView1.DataSource = GetDataSource();
            gridView1.DataBind();
        }
        else
        {
            gridView1.DataSource = (DataTable)Session[key];
            gridView1.DataBind();
        }

    }
    protected DataTable GetDataSource()
    {
        try
        {
            DataTable dt = new DataTable();
            dt = new DataTable();
            dt.Columns.Add("ID", typeof(int)).AutoIncrement = true;
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Age", typeof(int));
            DataColumn[] keys = new DataColumn[2];
            keys[0] = dt.Columns["ID"];
            dt.PrimaryKey = keys;
            dt.Rows.Add("1", "first object", 34);
            dt.Rows.Add("2", "second object", 24);
            dt.Rows.Add("3", "third object", 34);
            dt.Rows.Add("4", "fourth object", 24);
            dt.Rows.Add("5", "fifth object", 34);
       
            Session[key] = dt;
            return dt;
        }
        catch
        {
            return null;
        }
    }
    protected void btnMove_Click(object sender, EventArgs e)
    {
        try
        {
            DataTable dtMain = Session[key] as DataTable;
            //copy the schema of source table
            DataTable dtClone = dtMain.Clone();
            foreach (GridViewRow gv in gridView1.Rows)
            {
                CheckBox chk = gv.FindControl("chkSelect") as CheckBox;
                HiddenField hdValue = gv.FindControl("hdValue") as HiddenField;
                if (chk.Checked)
                {
                    //get only the rows you want
                    DataRow[] results = dtMain.Select("ID=" + hdValue.Value + "");
                    //populate new destination table
                    foreach (DataRow dr in results)
                    {
                        dtClone.ImportRow(dr);
                    }
                }
                gridView2.DataSource = dtClone;
                gridView2.DataBind();
            }
        }
        catch
        {
            BindGridView();
        }

    }
}

How To Extract Number from string

In this post i will show how to extract number from string using Regular expression.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExtractNumber.aspx.cs" Inherits="ExtractNumber" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtInput" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnExtract" runat="server" Text="ExtractNumber" OnClick="btnExtract_Click" /><br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ExtractNumber : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnExtract_Click(object sender, EventArgs e)
    {
        lblMessage.Text = ExtractNumbers(txtInput.Text);

    }
    public  string ExtractNumbers(string expr)
    {
        return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
    }
}

Wednesday, April 1, 2009

How To create Cascade dropdownlist using asp.net callback.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AppCallBack.aspx.cs" Inherits="AppCallBack" %>

<!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></title>

   <script type="text/javascript">

       function ReceiveServerData(arg, context) {
           var cmd_content = arg.split(',');
           if (cmd_content[0] == 'LoadSubCategory') {
               document.getElementById('ddlSubcategories').innerHTML = cmd_content[1];
           }
           else {

               document.getElementById('grvProducts').innerHTML = cmd_content[1];

           }

       }
       function CallSrv(ddl) {
           if (ddl.id == 'ddlCategories') {

               if (ddl.value != 'Select') {
                   CallServer('LoadSubCategory' + ',' + ddl.value, '');

               }

           }
           else {
               CallServer('LoadProducts' + ',' + ddl.value, '');
           }

       }

   </script>

</head>
<body>
   <form id="form1" runat="server">
   <div>
       <b>Categories:</b>
       <br />
       <asp:DropDownList ID="ddlCategories" runat="server" Width="100" onchange="CallSrv(this);">
       </asp:DropDownList>
       <br />
       <b>Subcategories</b>:
       <div id="ddlSubcategories">
       </div>
       <b>Products:</b>
       <div id="grvProducts">
       </div>
   </div>
   </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.IO;

public partial class AppCallBack : System.Web.UI.Page, ICallbackEventHandler
{
    public string RenderedOutput = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        ClientScriptManager scriptMgr = Page.ClientScript;
        String cbReference = scriptMgr.GetCallbackEventReference(this, "arg", "ReceiveServerData", "");
        String callbackScript = "function CallServer(arg, context) {" + cbReference + "; }";
        scriptMgr.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
        if (!Page.IsPostBack)
        {
            //Load Products Data
            this.ddlCategories.Items.Add("Select");
            this.ddlCategories.Items.Add("Autos");
            this.ddlCategories.Items.Add("Electronics");

        }

    }
    public void RaiseCallbackEvent(string eventArgument)
    {
        string[] commands = eventArgument.Split(",".ToCharArray());
        if (commands[0].Equals("LoadSubCategory"))
        {
            DropDownList ddlSubcategories = new DropDownList();
            switch (commands[1])
            {
                case "Autos":
                    ddlSubcategories.Items.Add("Cars");
                    ddlSubcategories.Items.Add("Bikes");
                    break;
                case "Electronics":
                    ddlSubcategories.Items.Add("Computers");
                    ddlSubcategories.Items.Add("TV");
                    break;

            }
            ddlSubcategories.Attributes.Add("onchange", "CallSrv(this);");
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            ddlSubcategories.RenderControl(htw);
            this.RenderedOutput = "LoadSubCategory," + sb.ToString();

        }
        else if (commands[0].Equals("LoadProducts"))
        {

            DataTable dtProducts = new DataTable();
            dtProducts.Columns.Add("Name");
            dtProducts.Columns.Add("Description");
            dtProducts.Columns.Add("Price");
            DataRow drProduct;
            switch (commands[1])
            {
                case "Cars":
                    drProduct = dtProducts.NewRow();
                    drProduct["Name"] = "Car1";
                    drProduct["Description"] = "XXX CCC";
                    drProduct["Price"] = "$1000";
                    dtProducts.Rows.Add(drProduct);
                    drProduct = dtProducts.NewRow();
                    drProduct["Name"] = "Car2";
                    drProduct["Description"] = "YYY CC";
                    drProduct["Price"] = "$800";
                    dtProducts.Rows.Add(drProduct);
                    break;

                case "Bikes":
                    drProduct = dtProducts.NewRow();
                    drProduct["Name"] = "Bike1";
                    drProduct["Description"] = "XXX CCC";
                    drProduct["Price"] = "$100";
                    dtProducts.Rows.Add(drProduct);
                    drProduct = dtProducts.NewRow();
                    drProduct["Name"] = "Bike2";
                    drProduct["Description"] = "YYY CC";
                    drProduct["Price"] = "$150";
                    dtProducts.Rows.Add(drProduct);
                    break;

                case "Computers":
                    drProduct = dtProducts.NewRow();
                    drProduct["Name"] = "Computer1";
                    drProduct["Description"] = "P4 ";
                    drProduct["Price"] = "$400";
                    dtProducts.Rows.Add(drProduct);
                    drProduct = dtProducts.NewRow();
                    drProduct["Name"] = "Computer2";
                    drProduct["Description"] = "P III";
                    drProduct["Price"] = "$350";
                    dtProducts.Rows.Add(drProduct);
                    break;

                case "TV":
                    drProduct = dtProducts.NewRow();
                    drProduct["Name"] = "TV1";
                    drProduct["Description"] = "Flat";
                    drProduct["Price"] = "$600";
                    dtProducts.Rows.Add(drProduct);
                    drProduct = dtProducts.NewRow();
                    drProduct["Name"] = "TV2";
                    drProduct["Description"] = "B &W";
                    drProduct["Price"] = "$550";
                    dtProducts.Rows.Add(drProduct);
                    break;

            }

            GridView grvProducts = new GridView();
            grvProducts.DataSource = dtProducts;
            grvProducts.DataBind();
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            grvProducts.RenderControl(htw);
            this.RenderedOutput = "LoadProducts," + sb.ToString();

        }

    }
    public string GetCallbackResult()
    {

        return RenderedOutput;

    }
}