Wednesday, June 27, 2012

ASP.NET Page Life Cycle

ASP.NET Page Life Cycle

  1. PreInit
  2. Init
  3. InitComplete
  4. Preload
  5. Load
  6. Control Events
  7. Load Complete
  8. PreRender
  9. PreRenderComplete
  10. SaveStateComplete
  11. Render
  12. Unload
 
The first stage in the page life cycle is initialization. This is fired after the page's control tree has been successfully created. All the controls that are statically declared in the .aspx file will be initialized with the default values. Controls can use this event to initialize some of the settings that can be used throughout the lifetime of the incoming web request.

After initialization, page framework loads the view state for the page. Viewstate is a collection of name/value pairs, where control's and page itself store information that is persistent among web requests. It contains the state of the controls the last time the page was processed on the server. By overriding LoadViewState() method, component developer can understand how Viewstate is restored.

Once Viewstate is restored, control will be updated with the client side changes. It loads the posted data values. The PostBackData event gives control a chance to update their state that reflects the state of the HTML element on the client.

At the end of the posted data changes event, controls will be reflected with changes done on the client. At this point, load event is fired.

Key event in the life cycle is when the server-side code associated with an event triggered on the client. When the user clicks on the button, the page posts back. Page framework calls the RaisePostBackEvent. This event looks up for the event handler and run the associated delegate.

After Postback event, page prepares for rendering. PreRender event is called. This is the place where user can do the update operations before the Viewstate is stored and output is rendered. Next stage is saving view state, all the values of the controls will be saved to their own Viewstate collection. The resultant Viewstate is serialized, hashed, base24 encoded and associated with the _Viewstate hidden field.

Next the render method is called. This method takes the HtmlWriter object and uses it to accumulate all HTML text to be generated for the control. For each control the page calls the render method and caches the HTML output. The rendering mechanism for the control can be altered by overriding this render method.

The final stage of the life cycle is unload event. This is called just before the page object is dismissed. In this event, you can release critical resources you have such as database connections, files, graphical objects etc. After this event browser receives the HTTP response packet and displays the page.


Creating and Using DLL in Asp.net C#

We have to create DLL with the help of Class Library, and call in a program, here are the steps to create and how it works with the help of an example.
1st Step->open windows application we have to choose Class Library option on the right hand side under the template option and name them Createdll.
CREATE DLL
 
After doing this we have to write a piece of code in .cs file, for the application like Add, subtracts and multiplies. Don’t forget to include the namespace as we have mentioned as namespace CreateDll.  And create a class name as math, under that class you can place a piece of code for Function Add, similarly for Subtract and multiply, as shown below.
 
 
namespace Createdll
{
    public class maths
    {
     //using add function and taking two parameters a and b.
 
        public static long add(long a, long b     
       {
            return (a + b);//return sum of a and b.
        }
 
        public static long sub(long a, long b)
        {
            return (a - b);//return minus of a and b.
        }
        public static long mul(long a, long b)
        {
            return (a * b);//return multiply of a and b.
        }
    }
}
 
 
Next important part is how to build and add references  to the dll.For Building an DLL Just Press F5 or we can click on the file option under that we will find debug option once we click it will be build automatically.
Under the Solution explorer on the right hand side of the corner we can easily see an option like reference as shown below:
 
 
Adding reference of dll created
 
 
Once you click on option then u will get a box like Add References  under that you have to click Browse you need to ADD ur application where ur application Create DLL is placed then click bin then ur name of The application like as shown with the help of arrow.
Adding reference of dll created
After adding reference to createDll library, you can see it as an available namespace as shown below in the screenshot
Reference of DLL added
Next important part is we have to call that CREATE DLL in our application, for that we have to open new windows project  and create a form like that as shown as below .
using created dll
As soon as we have created the Form like above next we have to write a piece of code under the Add, subtract, multiply and clear button.
Don’t forget to place a name space CreateDll same as the DLL which we want to access here with the help of DLL, as follows.
 using Createdll;
place a piece of code under the various button click
namespace irfandll
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
        }
 
        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                long a, b;
//assigning values of text boxes in variable a and b respectively.
                a = long.Parse(txtInput1.Text);
                b = long.Parse(txtInput2.Text);
//using add method of maths class I had created in class library (Createdll)
                txtInput3.Text = maths.add(a, b).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 
        private void btnSubtract_Click(object sender, EventArgs e)
        {
            long a, b;
//assigning values of text boxes in variable a and b respectively.
 
            a = long.Parse(txtInput1.Text);
            b = long.Parse(txtInput2.Text);
//using add method of maths class I had created in class library (Createdll)
 
            txtInput3.Text = maths.sub(a, b).ToString();
 
        }
 
 
 
        private void btnClear_Click(object sender, EventArgs e)
        {
            txtInput1.Text = "";
            txtInput2.Text = "";
            txtInput3.Text = "";
        }
        private void btnMultiply_Click(object sender, EventArgs e)
        {
            long a, b;
//assigning values of text boxes in variable a and b respectively.
 
            a = long.Parse(txtInput1.Text);
            b = long.Parse(txtInput2.Text);
//using add method of maths class I had created in class library (Createdll)
 
            txtInput3.Text = maths.mul(a, b).ToString();
        }
    }
}
 
 
After this process we have to build our application with the help of F5.we will see the output like as shown below
In these of the text field we need to check by putting various no in the text box and one by one we have to check the entire button as Add, Subtract, Multiply, and Clear button.
The desired output will be like that as shown below in the screen shot.

GridView inside GridView in ASP.Net C#(Nested GridView)

GridView inside GridView in ASP.Net-- C# (Nested GridView)

Here I am focusing on how we can use GridView inside GridView i.e nested gridview. Let’s see the brief demonstraton on use of nested gridview.
Step 1: Open Visual Studio and select new project from File menu and select website.
Step 2: After create successful new project drag gridview from toolbox and drop it on web page where you want.
After successfully drag gridview on the page you can perform many tasks such as you can edit format of gridview , edit columns and many more.
GridView inside GridView in ASP.Net (Nested GridView)
Here when you click on the Auto Format then following window will be appear where you have more choice like
GridView inside GridView in ASP.Net (Nested GridView)
Now when you click on edit columns then following window will be appear where you can add different types of fields
GridView inside GridView in ASP.Net (Nested GridView)
Here I am adding three template field.
  Step 3:  Now for performing nested gridview or gridview inside gridview you can write the following code.
<%-- Parent gridview --%>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
           
            CellPadding="4" EnableModelValidation="True"
            ForeColor="#333333" GridLines="None" onrowcommand="GridView1_RowCommand" onrowcancelingedit="GridView1_RowCancelingEdit"
           
            >
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="Department_Id">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("did") %>'>asp:TextBox>
                    EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("did") %>'>asp:Label>
                    ItemTemplate>
                asp:TemplateField>
                <asp:TemplateField HeaderText="Department_Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("department") %>'>asp:TextBox>
                    EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("department") %>'>asp:Label>
                    ItemTemplate>
                asp:TemplateField>
               
                <asp:TemplateField HeaderText = "Details">
                     <ItemTemplate>
 
                       <asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%# Container.DataItemIndex%>' />
                       <asp:Button ID ="Cancel" Text="Cancel" runat= "server" CommandName= "Cancel" CommandArgument='<%# Container.DataItemIndex%>' Visible="false" />
                     <%--child gridview with bound fields --%>
                       <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
             CellPadding="4" EnableModelValidation="True"
            ForeColor="#000000" GridLines="Both">
                        <Columns>
                          <asp:BoundField DataField="Emp_Id" HeaderText= "Emp_Id" >
                          <ItemStyle Width = "20%" />
                          asp:BoundField>
                          <asp:BoundField DataField="Dep_Name" HeaderText= "Dep_Name" >
                          <ItemStyle Width = "20%" />
                          asp:BoundField>
                          <asp:BoundField DataField="Name" HeaderText= "Name" >
                          <ItemStyle Width = "20%" />
                          asp:BoundField>
                          <asp:BoundField DataField="Address" HeaderText= "Address" >
                          <ItemStyle Width = "20%" />
                          asp:BoundField>
                          <asp:BoundField DataField="Department" HeaderText= "Department" >
                          <ItemStyle Width = "20%" />
                          asp:BoundField>
                          <asp:BoundField DataField="Designation" HeaderText= "Designation" >
                          <ItemStyle Width = "20%" />
                          asp:BoundField>
                          <asp:BoundField DataField="Technology" HeaderText= "Technology" >
                          <ItemStyle Width = "20%" />
                          asp:BoundField>
                         Columns>
                         <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
                        asp:GridView>
                    ItemTemplate>
          
                asp:TemplateField>
            Columns>
            <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
        asp:GridView>
The Deisgn of GridView as follows
GridView inside GridView in ASP.Net (Nested GridView)
After the design is complete write the following code in .cs file.
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ///// bind data with parent gridview when page first time loaded
            SqlConnection con = new SqlConnection(ConnectionString.ConnString());
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand("select did , Department from tblDepartment", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
           
        }
 
    }
 
    ///


    /// This event raised when button clicked within GridView
    ///

 
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        /// takes the command argument row index
        int rowindex = Convert.ToInt32(e.CommandArgument.ToString());
        //// find child gridview control
        GridView grv = (GridView)GridView1.Rows[rowindex].FindControl("GridView2");
 
        ////  text for which details display
        Label lbl=  (Label) GridView1.Rows[rowindex].FindControl("Label2");
        GridView1.Rows[rowindex].FindControl("Cancel").Visible = false;
       
        ////
        if (e.CommandName == "Details")
        {
            GridView1.Rows[rowindex].FindControl("Cancel").Visible = true
            GridView1.Rows[rowindex].FindControl("btn_Show").Visible = false;   
            SqlConnection con = new SqlConnection(ConnectionString.ConnString());
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter();
            DataSet ds = new DataSet();
            if (lbl.Text == "HR Department")
            {
                da.SelectCommand = new SqlCommand("Select * from tblHR", con);
                da.Fill(ds);
            }
            else if (lbl.Text == "Sales Department")
            {
                da.SelectCommand = new SqlCommand("Select * from tblSales", con);
                da.Fill(ds);
            }
            else
            {
                da.SelectCommand = new SqlCommand("Select * from tblTechnical", con);
                da.Fill(ds);
            }
            ////// bind data with child gridview
            grv.DataSource = ds;
            grv.DataBind();
            grv.Visible = true;
        }
        else
        {
            //// child gridview  display false when cancel button raise event
            grv.Visible = false;
            GridView1.Rows[rowindex].FindControl("btn_Show").Visible = true;
        }
    }
 
    ///


    /// row cancel event when clicked on cancel button
    ///

 
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
 
    }
}
When you debug this code and click on details button then output will be
GridView inside GridView in ASP.Net (Nested GridView)
If want see all details of column Department_Name then you can see after clicking all details button.
GridView inside GridView in ASP.Net (Nested GridView)

Conclusion:

Here we are taking two gridview control first is parent gridview and second one is child gridview control. Parent gridview control contain three category HR department, Technical department and sales department, and all the category have some information which are showing in child gridview control when click on Details button.