Parent Child Relationship in Javascript

In this post i will show how to call parent window function from child window and how to pass value from child window to parent window. Parent.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Parent.aspx.cs" Inherits="Parent" %>

<!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 language="Javascript" type="text/javascript">
     function CallAlert() {
         alert("This is parent window's alert function.");
     }
     function ButtonClickByChild() {
         alert("Click by child.");
     }
     var newwindow;
     function poptastic(url) {
         newwindow = window.open(url, 'name', 'height=400,width=700');
         if (window.focus) {
             newwindow.focus()
         }
     }

 </script>

</head>
<body>
 <form id="form1" runat="server">
 <div>
     <asp:Button ID="btnParent" runat="server" OnClientClick="ButtonClickByChild();" Text="Parent Button Clicked By Child" />
     <asp:TextBox ID="txtParent" runat="server"></asp:TextBox>
     <a href="javascript:poptastic('Child.aspx');">Open Child Window</a>
 </div>
 </form>
</body>
</html>

Child.aspx

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

<!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">
     //Method call parent window function
     function ParentWindowFunction() {
         window.opener.CallAlert();
         return false;
     }
     //Method pass value from child to parent
     function SetParentText() {
         window.opener.document.getElementById("txtParent").value =
                         document.getElementById("txtChild").value;
         window.opener.document.getElementById("btnParent").click();
         //Call this function in real application
         // window.close();
         return false;

     }
 </script>

</head>
<body>
 <form id="form1" runat="server">
 <div>
     <asp:TextBox ID="txtChild" runat="server"></asp:TextBox>
 </div>
 <asp:Button ID="btnChild1" runat="server" Text="Pass Value To Parent" OnClientClick="return SetParentText();" />
 <asp:Button ID="btnChild2" runat="server" Text="Call Parent Function" OnClientClick="ParentWindowFunction();" />
 </form>
</body>
</html>

How To Create Composite Control

ASP.NET includes the TextBox control and the Validation controls which can be combined together to perform user input validation. The restriction is that the developer has to use two different controls to perform a simple validation. In this post are going to create a custom TextBox control which will use Required field validation controls and reduce the complexity of using multiple controls.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AspTextBox
{
 [DefaultProperty("Text")]
 [ToolboxData("<{0}:AspTextBox runat=server></{0}:AspTextBox>")]
 public class AspTextBox : CompositeControl, INamingContainer
 {
     private TextBox _myTextBox = new TextBox();
     private RequiredFieldValidator _myRFV = new RequiredFieldValidator();
     protected override void OnInit(EventArgs e)
     {
         base.OnInit(e);
    
     
         _myTextBox.ID = this.UniqueID;
         _myRFV.ControlToValidate = _myTextBox.ID;
         _myRFV.Display = ValidatorDisplay.Dynamic;
         _myRFV.EnableClientScript = true;
         Controls.Add(_myRFV);

     }
     public bool isRequired
     {
         get { return _myRFV.Enabled; }
         set { _myRFV.Enabled = value; }
     }

     public String ErrorMessage
     {
         get { return _myRFV.ErrorMessage; }
         set { _myRFV.ErrorMessage = value; }
     }



     protected override void CreateChildControls()
     {
         this.Controls.Add(_myTextBox);
         this.Controls.Add(_myRFV);
     }

     protected override void Render(HtmlTextWriter writer)
     {
         _myTextBox.RenderControl(writer);
         if (_myRFV.IsValid == false) { writer.WriteBreak(); }
         _myRFV.RenderControl(writer);
     }
 }


}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<%@ Register Assembly="AspTextBox" Namespace="AspTextBox" 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">
  <cc1:AspTextBox ErrorMessage="Textbox is Required " isRequired="true" ID="AspTextBox1"
      runat="server" />
  </br>
  <asp:Button ID="Button1" runat="server" Text="Validate" />
  </form>
</body>
</html>

How To find control inside EmptyTemplate

In this post i will show . How to add new row in gridview. How to find control inside EmptyDataTemplate
<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="Gridview.aspx.cs"
   Inherits="JQueryTest.Gridview" %>

<%@ Register Src="Grid3S.ascx" TagName="Grid3S" TagPrefix="uc1" %>
<!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="grdPrice" DataKeyNames="ID" runat="server" AutoGenerateColumns="False"
           Width="200px" ShowHeader="False" OnRowCommand="grdPrice_RowCommand" OnRowDataBound="grdPrice_RowDataBound"
           CellPadding="4" ForeColor="#333333" GridLines="None">
           <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
           <Columns>
               <asp:TemplateField>
                   <FooterTemplate>
                       <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Insert">Insert</asp:LinkButton>
                   </FooterTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="3S">
                   <ItemTemplate>
                       <asp:Label ID="lbl3S" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
                   </ItemTemplate>
                   <FooterTemplate>
                       <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                   </FooterTemplate>
               </asp:TemplateField>
           </Columns>
           <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
           <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
           <EmptyDataTemplate>
               <asp:TextBox ID="txtEmptyData" runat="server"></asp:TextBox>
           </EmptyDataTemplate>
           <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
           <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
           <EditRowStyle BackColor="#999999" />
           <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
       </asp:GridView>
       <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
       <asp:Button ID="btnAdd" runat="server" Text="Add More" OnClick="btnAdd_Click" />
   </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;

namespace JQueryTest
{
    public partial class Gridview : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }
        private void BindGridView()
        {
            DataTable dt = new DataTable();
            dt = (DataTable)Session["MyDataSource"];
            grdPrice.DataSource = GetDataSource();
            grdPrice.DataBind();

        }
        protected DataTable GetDataSource()
        {
            const string key = "MyDataSource";
            DataTable dt = Session[key] as DataTable;
            if (dt == null)
            {
                dt = new DataTable();
                dt.Columns.Add("ID", typeof(int)).AutoIncrement = true;
                dt.Columns.Add("Name", typeof(string));
                DataColumn[] keys = new DataColumn[2];
                keys[0] = dt.Columns["ID"];
                dt.PrimaryKey = keys;

                dt.Rows.Add("1", "first object");
                dt.Rows.Add("2", "second object");
                Session[key] = dt;

            }
            return dt;
        }
        protected void AddData()
        {
            DataTable dt = (DataTable)Session["MyDataSource"];
            DataRow rw = dt.NewRow();
            TextBox txt = (TextBox)grdPrice.FooterRow.Cells[1].FindControl("TextBox2");
            if (txt.Text != "")
            {


                rw[1] = txt.Text;
                dt.Rows.Add(rw);
                Session["MyDataSource"] = dt;
            }
        }
        protected void grdPrice_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "Insert")
            {
                AddData();
                grdPrice.ShowFooter = false;
                BindGridView();
                btnAdd.Enabled = true;

            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            GridViewRow gvr;
            if (grdPrice.Rows.Count == 0)
            {
                Table tbl = (Table)grdPrice.Controls[0];
                gvr = (GridViewRow)tbl.Controls[0];
                DataTable dt = (DataTable)Session["MyDataSource"];
                DataRow rw = dt.NewRow();
                TableCell cell = gvr.Cells[0];
                TextBox txtEmptyData = (TextBox)cell.FindControl("txtEmptyData");
                rw[1] = txtEmptyData.Text;
                dt.Rows.Add(rw);
                Session["MyDataSource"] = dt;
                grdPrice.ShowFooter = false;
                BindGridView();

            }
            else
            {
                // when there are rows returned you can reference the gridviewrow by grabbing the footerrow
                gvr = (GridViewRow)grdPrice.FooterRow;
                grdPrice.ShowFooter = true;
                BindGridView();
                btnAdd.Enabled = false;
            }



        }
        DataKey key;


        protected void grdPrice_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='none';";
                e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(grdPrice, "Select$" + e.Row.RowIndex);
            }

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {

            try
            {

                GridViewRow gv = grdPrice.SelectedRow;

                key = grdPrice.DataKeys[gv.RowIndex];
                DataTable dt = (DataTable)Session["MyDataSource"];

                DataRow rw = dt.Rows.Find(int.Parse(key.Value.ToString()));
                rw.Delete();
                dt.AcceptChanges();
                BindGridView();
                grdPrice.SelectedIndex = -1;

            }
            catch
            {
                BindGridView();
            }

        }

      


    }
}

How To Create MultiColum Dropdownlist using DropDownExtender Control


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

<%@ 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>
 <style>
     .invisibleColumn
     {
         display: none;
         width: 0px;
     }
     body
     {
         font-family: Arial;
         font-size: 12px;
     }
 </style>
</head>
<body>
 <form id="form1" runat="server">
 <asp:ScriptManager ID="ScriptManager1" runat="server">
 </asp:ScriptManager>
 <div>
     <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>
 </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 MultiColumnDDL : 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)
         return;

     e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';"
     + "this.originalBackgroundColor=this.style.backgroundColor;"
     + "this.style.backgroundColor='#bbbbbb';";

     e.Row.Attributes["onmouseout"] =
     "this.style.backgroundColor=this.originalBackgroundColor;";

     e.Row.Attributes["onclick"] =
     ClientScript.GetPostBackClientHyperlink(this.FriendGridView,
      "Select$" + e.Row.RowIndex);
 }
 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; }

 }
}

How To Create Multi Column Dropdownlist

In this post i will show how to create multi column dropdown list using asp.net .In your server side code, use the \u00A0 character as your padding character. Create calculated columns in your data table to set as the text field for the dropdownlist.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiCoulmn.aspx.cs" Inherits="MultiCoulmn" %>

<!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:DropDownList ID="ddlUser" runat="server">
     </asp:DropDownList>
 </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 MultiCoulmn : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       List<Friend> friends = GetFriends();
       foreach (Friend f in friends)
       {

           string text = string.Format("{0}|{1}", f.Name.PadRight(10, '\u00A0'), f.Description.PadRight(10,'\u00A0'));
           ddlUser.Items.Add(new ListItem(text, f.Id.ToString()));

       }
       ddlUser.DataBind();


   }
   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;


   }
}
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; }

   }
}

How To Create control at runtime using javascript

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

<!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 addElement() {
            var ni = document.getElementById('myDiv');
            var numi = document.getElementById('theValue');
            var num = (document.getElementById('theValue').value - 1) + 2;
            numi.value = num;
            var newdiv = document.createElement('div');
            var divIdName = 'my' + num + 'Div';
            newdiv.setAttribute('id', divIdName);
            newdiv.innerHTML = "Element Number " + num + " has been added! <a href=\"javascript:;\" onclick=\"removeElement(\'" + divIdName + "\')\">Remove the element &quot;" + divIdName + "&quot;</a>";

            ni.appendChild(newdiv);
        }
        function removeElement(divNum) {
            var d = document.getElementById('myDiv');
            var olddiv = document.getElementById(divNum);
            d.removeChild(olddiv);
        }
       
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="hidden" value="0" id="theValue" />
    <p><a href="javascript:;" onclick="addElement();">Add Some Elements</a></p>
    <div id="myDiv"> </div>

    </div>
    </form>
</body>
</html>

How to Move a Text Box on Button Click

<%@ 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>

  <script type="text/javascript">
      function moveTextBox() {
          var objTextbox = document.getElementById("theText");
          objTextbox.style.pixelLeft += 100;
      }
  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <input id="Button1" style="" type="button" value="Button" onclick="moveTextBox()"
          runat="server" />
      <input style="left: 166px; position: absolute; top: 98px" id="theText" type="text" />
  </div>
  </form>
</body>
</html>

How To attach event to runtime created control

In this post i will show how to create control at run time and attached event to control.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Untitled</title>
</head>
<body>

    <script type="text/javascript">
        function addRow() {
            var table = document.getElementById('table1');
            var TR = table1.insertRow();
            var TD = TR.insertCell();
            TD.innerHTML = 'Row added';
            TD.onclick = function() { alert('This is onclick') };
            TD.onmouseover = function() { alert('This is mouseover') };

        }
    </script>

    <table id='table1'>
    </table>
    <br>
    <input type='button' value='Add Row' onclick='addRow()' />
</body>
</html>

How To Find Position of Span Tag

<!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>
    <title></title>
       <script type="text/javascript">
      function whereAmI( oLostObject )
      {
        var iOffsetTop = 0;
        var iOffsetLeft = 0;
        while( oLostObject.parentNode )
        {
          iOffsetTop += oLostObject.offsetTop;
          iOffsetLeft += oLostObject.offsetLeft;
          oLostObject = oLostObject.parentNode;
        }  
        var sCoordinates = ( iOffsetLeft + "," + iOffsetTop );
        alert( sCoordinates );
        return sCoordinates;
      }
    </script>

</head>
<body>
<div style="text-align:right">
      <div style="padding:50px">
        <span style="positiosn:absolute; top 50px; left:100px;" onmouseover="whereAmI( this )" >I am Here.</span>
      </div>
    </div>
</body>
</html>

How To add event to runtime created control -Javascript

<html>
<head>
      <title>Untitled</title>
</head>

<body>
<script>
function addRow(){
      var table = document.getElementById('table1');
      var TR = table1.insertRow();
      var TD = TR.insertCell();
      TD.innerHTML = 'Row added';
      TD.onclick= function(){ alert( 'This is onclick') };
      TD.onmouseover= function(){ alert( 'This is mouseover') };
      
      }
</script>

<table id='table1'>

</table>
<br>
<input type='button' value='Add Row' onclick='addRow()'>
</body>
</html>

How To Display Hierarchical Data in the DropDownList

In this Post I will demonstrate how you can use a simple ASP.NET DropDownList control to display hierarchical data.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx.cs" Inherits="Default6" %>

<!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>Untitled Page</title>
    <style type="text/css">
    .ParentChild
   
    {
    color:red;
   
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div>
                <asp:DropDownList ID="ddlCategories" runat="server" OnPreRender="ddlCategories_PreRender" />
                <asp:RequiredFieldValidator ID="rfvCategories" runat="server" ControlToValidate="ddlCategories"
                    InitialValue="Please select " ErrorMessage="Please select " />
                <br />
                <br />
                <asp:Button ID="Button1" runat="server" Text="Select" OnClick="Button1_Click" />
                <asp:Label ID="lblMessage" runat="server" />
            </div>
        </div>
    </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default6 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }

    private void Bind()
    {
        DataSet ds = Data() as DataSet;

        foreach (DataRow row in ds.Tables[0].Rows)
        {

            int ParentID = Convert.ToInt32(row["ID"]);

            string ParentName = row["Name"] as String;

            ddlCategories.Items.Add(new ListItem(String.Empty, String.Empty));

            ddlCategories.Items.Add(new ListItem(ParentName, "0"));

            ddlCategories.Items.Add(new ListItem(String.Empty, String.Empty));

            DataRow[] childRows = ds.Tables[1].Select("ID = " + ParentID);

            foreach (DataRow childRow in childRows)
            {

                ddlCategories.Items.Add(new ListItem((string)childRow["Qul"], (childRow["ID"].ToString())));

            }

        }


    }
    private DataSet Data()
    {

        DataTable dt = new DataTable();
        dt.Columns.Add("Id", typeof(int));
        dt.Columns.Add("Name", typeof(string));

        dt.Rows.Add(new object[] { 1, "aaaa" });
        dt.Rows.Add(new object[] { 2, "bbbb" });
        dt.Rows.Add(new object[] { 3, "cccc" });
        dt.TableName = "Parent";




        DataTable dtc = new DataTable();
        dtc.Columns.Add("Id", typeof(int));
        dtc.Columns.Add("Qul", typeof(string));

        dtc.Rows.Add(new object[] { 1, "child1" });
        dtc.Rows.Add(new object[] { 1, "chid12" });
        dtc.Rows.Add(new object[] { 1, "child13" });
        dtc.Rows.Add(new object[] { 2, "child21" });
        dtc.Rows.Add(new object[] { 2, "child22" });
        dtc.Rows.Add(new object[] { 3, "child31" });
        dtc.Rows.Add(new object[] { 3, "child32" });
        dtc.Rows.Add(new object[] { 3, "child32" });
        dtc.TableName = "Child";


        DataSet ds = new DataSet();

        ds.Tables.Add(dt);
        ds.Tables.Add(dtc);
        Session["Parent"] = dt;

        return ds;

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        {

            string selectedValue = String.Empty;



            if (Page.IsValid)
            {

                selectedValue = ddlCategories.SelectedValue;



                if (!String.IsNullOrEmpty(selectedValue) && selectedValue.Equals("0") == false)
                {

                    lblMessage.Text = "Selected Value is " + "#" + selectedValue;

                }

                else
                {

                    lblMessage.Text = "Please select a value";

                }

            }
        }
    }
    protected void ddlCategories_PreRender(object sender, EventArgs e)
    {
        foreach (ListItem item in ddlCategories.Items)
        {

            if (item.Value.Equals("0"))
            {

                item.Attributes.Add("class", "ParentChild");

            }

        }
    }
}

Real World GridView: Excel-like Frozen Headers for ASP.NET 2.0

Check out this link for how to create Excel like gridview Link

GridView Sorting And Paging

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

<!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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
               AutoGenerateColumns="true"  OnDataBound="GridView1_DataBound"
               OnPageIndexChanging="GridView1_PageIndexChanging" OnSorting="GridView1_Sorting">
               <PagerTemplate>
                   <asp:Button ID="btnFirst" runat="server" Text="<< First" CommandArgument="First"
                       CommandName="Page" />
                   <asp:Button ID="btnPrev" runat="server" Text="< Previous" CommandArgument="Prev"
                       CommandName="Page" />
                   Page
                   <asp:DropDownList ID="ddlPages" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlPages_SelectedIndexChanged">
                   </asp:DropDownList>
                   of
                   <asp:Label ID="lblPageCount" runat="server"></asp:Label>
                   <asp:Button ID="btnNext" runat="server" Text="Next >" CommandArgument="Next" CommandName="Page" />
                   <asp:Button ID="btnLast" runat="server" Text="Last >>" CommandArgument="Last" CommandName="Page" />
               </PagerTemplate>
           </asp:GridView>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        } 

    }

    private void BindGrid()
    {
       
        GridView1.DataSource = GetDataSet();
        GridView1.DataBind();
    }
    protected void GridView1_DataBound(Object sender, EventArgs e)
    {
        GridViewRow gvrPager = GridView1.BottomPagerRow;

        if (gvrPager == null) return;

        // get your controls from the gridview
        DropDownList ddlPages =
        (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
        Label lblPageCount =
        (Label)gvrPager.Cells[0].FindControl("lblPageCount");

        if (ddlPages != null)
        {
            // populate pager
            for (int i = 0; i < GridView1.PageCount; i++)
            {

                int intPageNumber = i + 1;
                ListItem lstItem =
                new ListItem(intPageNumber.ToString());

                if (i == GridView1.PageIndex)
                    lstItem.Selected = true;

                ddlPages.Items.Add(lstItem);
            }
        }

        int itemCount = 0;

        // populate page count
        if (lblPageCount != null)
        {

            //pull the datasource
            DataSet ds = GridView1.DataSource as DataSet;
            if (ds != null)
                itemCount = ds.Tables[0].Rows.Count;

            string pageCount = "<b>" + GridView1.PageCount.ToString() + "</b> (" + itemCount.ToString() + " Items)";
            lblPageCount.Text = pageCount;

        }

        Button btnPrev = (Button)gvrPager.Cells[0].FindControl("btnPrev");
        Button btnNext = (Button)gvrPager.Cells[0].FindControl("btnNext");
        Button btnFirst = (Button)gvrPager.Cells[0].FindControl("btnFirst");
        Button btnLast = (Button)gvrPager.Cells[0].FindControl("btnLast");

        //now figure out what page we're on
        if (GridView1.PageIndex == 0)
        {
            btnPrev.Enabled = false;
            btnFirst.Enabled = false;
        }
        else if (GridView1.PageIndex + 1 == GridView1.PageCount)
        {
            btnLast.Enabled = false;
            btnNext.Enabled = false;
        }
        else
        {
            btnLast.Enabled = true;
            btnNext.Enabled = true;
            btnPrev.Enabled = true;
            btnFirst.Enabled = true;
        }

    }
    protected void ddlPages_SelectedIndexChanged(Object sender, EventArgs e)
    {
        GridViewRow gvrPager = GridView1.BottomPagerRow;
        DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");

        GridView1.PageIndex = ddlPages.SelectedIndex;

        // a method to populate your grid
        BindGrid();
    }
    public DataSet GetDataSet()
    {

        DataTable dt = new DataTable("Company");
        DataRow dr;
        dt.Columns.Add(new DataColumn("accountNo", typeof(Int32)));
        dt.Columns.Add(new DataColumn("CompanyName", typeof(string)));
        dt.Columns.Add(new DataColumn("Address", typeof(Int32)));
        for (int i = 0; i <= 10; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = "Company" + i + Environment.NewLine + "Title" + i;
            dr[2] = i;
            dt.Rows.Add(dr);
        }

        DataSet ds = new DataSet();
        ds.Tables.Add(dt);
        return ds;
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataSet ds = GetDataSet();

        if (ds != null)
        {


            DataView dataView = new DataView(ds.Tables[0]);
            dataView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);

            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }

    }

    private DataSet GetMyDataSet()
    {
        throw new Exception("The method or operation is not implemented.");
    }

    string GetSortDirection(string sortBy)
    {

        string sortDir = " ASC";
        if (ViewState["sortBy"] != null)
        {
            string sortedBy = ViewState["sortBy"].ToString();

            if (sortedBy == sortBy)
            {
                //the direction should be desc
                sortDir = " DESC";

                //reset the sorter to null
                ViewState["sortBy"] = null;
            }
            else
            {
                //this is the first sort for this row
                //put it to the ViewState
                ViewState["sortBy"] = sortBy;

            }
        }
        else
        {
            //it's null, so this is the first sort
            ViewState["sortBy"] = sortBy;
        }
        return sortDir;

    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        //rebind using your bind routine
        BindGrid();
    }
}

How to create a Setup project for a Windows Service in Visual Basic .NET or in Visual Basic 2005

This article discusses how to create a Setup project for a Windows Service application. (Windows Service was formerly known as "NT service.") To do this, you must first create a solution that contains a simple Windows Service project. This project writes an entry to the application log. You then add a Setup project to the solution to install the Window Service. Finally, you start the service from within Visual Studio .NET Server Explorer. check out this link

101 LINQ Samples

if you're learning or curious about LINQ, MSDN has put together 101 LINQ samples to demo its core features. check out this linq 101 LINQ Samples

How to open ModalPopup inside ModalPopup



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

<!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>Untitled Page</title>
<style type="text/css">
.modalBackground
{
background-color:#f5f5f5;
filter:alpha(opacity=80);
opacity:0.7;
}
</style>
</head>
<body>
<form id="form1" runat="server">
    <asp:ScriptManager ID="A" runat="Server">
    </asp:ScriptManager>
    <%--Master Button--%>
    <asp:Button ID="btnOpen" Width="200px" runat="server" Text="Open Parent" CssClass="button"
        CausesValidation="False" OnClientClick="$find('mdlPopup').show(); return false;" />
    <%--Hidden Button--%>
    <asp:Button ID="btnShowPopup" runat="server" Style="display: none" />
    <%--Modalpopup extender For Parent--%>
    <ccl:ModalPopupExtender ID="mdlPopup" runat="server" TargetControlID="btnShowPopup"
        PopupControlID="pnlParent" CancelControlID="btnClose" BackgroundCssClass="modalBackground">
    </ccl:ModalPopupExtender>
    <%--Parent Panel--%>
    <asp:Panel ID="pnlParent" Style="display: none; position: absolute; width: 500px;
        border: solid 1px black; height: 400px; background-color: White; margin-left: 50px"
        runat="server" CssClass="modalpopup">
        <asp:UpdatePanel ID="updateParent" runat="Server">
            <ContentTemplate>
                <table>
                    <tr>
                        <td>
                            <asp:Button ID="btnParent" runat="server" Text="Open Child" CssClass="button" Width="200px"
                                CausesValidation="False" OnClientClick="$find('mdlChild').show(); return false;" />
                        </td>
                        <td>
                            Gender
                        </td>
                        <td>
                            <asp:DropDownList ID="ddl" runat="Server" AutoPostBack="True" OnSelectedIndexChanged="ddl_SelectedIndexChanged">
                                <asp:ListItem Text="Male" Value="Male"></asp:ListItem>
                                <asp:ListItem Text="Female" Value="Female"></asp:ListItem>
                            </asp:DropDownList>
                            <asp:Label ID="lbl" runat="Server"></asp:Label>
                        </td>
                    </tr>
                </table>
                <%--Close Button For Parent Modal Popup--%>
                <asp:Button ID="btnClose" runat="server" Text="Close" OnClientClick="$find('mdlPopup').hide(); return false;" />
                <%--Target Control Button For Child Modal--%>
                <asp:Button ID="btnChildTarget" runat="server" Style="display: none" />
                <ccl:ModalPopupExtender ID="mdlChild" runat="server" TargetControlID="btnChildTarget"
                    PopupControlID="pnlChild" CancelControlID="btnCloseChild" BackgroundCssClass="modalBackground">
                </ccl:ModalPopupExtender>
                <asp:Panel runat="server" ID="pnlChild" Style="display: none; width: 100%; border: solid 1px black;
                    height: 100%; background-color: White; margin-left: 10px">
                    <table>
                        <tr>
                            <td>
                                First Name
                            </td>
                            <td>
                                <asp:TextBox ID="txt" runat="Server"></asp:TextBox>
                            </td>
                        </tr>
                    </table>
                    <asp:Button ID="btnCloseChild" runat="server" Text="Close" OnClientClick="$find('mdlChild').hide(); return false;" />
                    <asp:Button ID="btnChild" runat="server" OnClick="btnChild_Click" Text="Send Value To Parent" /></asp:Panel>
            </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Panel>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

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

  }
  protected void btnResult_Click(object sender, EventArgs e)
  {
      mdlPopup.Show();

  }
  protected void Button3_Click(object sender, EventArgs e)
  {
      mdlPopup.Show();
      mdlChild.Show();
  }
  protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
  {
      lbl.Text = ddl.SelectedItem.Value;
  }
  protected void btnChild_Click(object sender, EventArgs e)
  {
      lbl.Text = txt.Text;
      mdlChild.Show();

  }
}