Saturday, August 30, 2014

ASP.NET Page Life Cycle

Init
This event happens in the ASP.NET page and can be used for:
Ø             Creating controls dynamically, in case you have controls to be created on runtime.
Ø             Any setting initialization.
Ø             Master pages and the settings.
Ø         In this section, we do not have access to viewstate, postedvalues and neither the controls are initialized.
Load
In this section, the ASP.NET controls are fully loaded and you write UI manipulation logic or any other logic over here.
Validate
If you have valuators on your page, you would like to check the same here.
Render
It’s now time to send the output to the browser. If you would like to make some changes to the final HTML which is going out to the browser, you can enter your HTML logic here.
Unload
Page object is unloaded from the memory.
                                                                                                                                          
Seq
Events
Controls Initialized
View state
Available
Form data
Available
What Logic can be written here?
1
Init
No
No
No
Note: You can access form data etc. by using ASP.NET request objects but not by Server controls.Creating controls dynamically, in case you   have controls to be   created on runtime. Any settinginitialization.Master pages and them settings. In this section, we do not have access to viewstate , posted values and neither the controls are initialized.
2
Load view state
Not guaranteed
Yes
Not guaranteed
You can access view state and any synch logic where you want viewstate to be pushed to behind code variables can be done here.
3
PostBackdata
Not guaranteed
Yes
Yes
You can access form data. Any logic where you want the form data to be pushed to behind code variables can be done here.
4
Load
Yes
Yes
Yes
This is the place where you will put any logic you want to operate on the controls. Like flourishing a combobox from the database, sorting data on a grid, etc. In this event, we get access to all controls,   viewstate and their posted values.
5
Validate
Yes
Yes
Yes
If your page has validators or you want to execute validation for your page, this is the right place to the same.
6
Event
Yes
Yes
Yes
If this is a post back by a button click or a dropdown change, then the relative events will be fired. Any kind of logic which is related to that event can be executed here.
7
Pre-render
Yes
Yes
Yes
If you want to make final changes to the UI objects like changing tree structure or property values, before these controls are saved in to view state.
8
Save view state
Yes
Yes
Yes
Once all changes to server controls are done, this event can be an opportunity to save control data in to view state.
9
Render
Yes
Yes
Yes
If you want to add some custom HTML to the output this is the place you can.
10
Unload
Yes
Yes
Yes
Any kind of clean up you would like to do here.

Saturday, August 9, 2014

DetailsView Control

DetailsView is a data control that displays the values of a single record from a data source in a table, where each data row represents a field of the record. It allows us to perform the operations like insert, edit, and update and delete records.
DetailsView has following important properties:
                     Property
                                                 Description
AutogenerateRows
Indicates whether rows are automatically generated
AutogenerateEditButton
Indicates whether edit button is automatically generated
AutogenerateDeleButton
Indicates whether delete button is automatically generated
AutogenerateInsertButton
Indicates whether insert button is automatically generated

DetailsView has the following important events:
Event
Description
ModeChanging
Raised whenever the mode is changing
ItemInserting
Raised when user click on insert button
ItemUpdating
Raised when user click on update button
ItemDeleting
Raised when user click on delete button
ItemCommand
Raised when user click on any button
PageIndexChanging
Raised when user change from one page to another

Example:-

In this article I am going to explain with example How to perform Bind, Insert, Edit, Update, Cancel , Delete and paging operation in DetailsView in asp.net using C#.

1.       First of all we need to create database in Sql server e.g. "dbEmp" and in this database create a table with the Columns and Data type as shown in image below and name it "Emp"


Column Name
Data Type
Emp_Id
int(Primary Key. So set Is Identity=True)
EmpName
varchar(100)
Age
int
Salary
decimal(10, 2)
City
varchar(100)
Address
varchar(500)

2.       Now In the web.config file create the connection string as:
<connectionStrings>
<add name="constr" connectionString "uid=sa;pwd=nagesh;database=nagesh;" providerName "System.Data.SqlClient"/>
            </connectionStrings>
3.       In the design page (.aspx) place a DetailsView data control from the visual studio's toolbox and configure it as shown below:
<div>
     <fieldset style="width:250px";>
    <legend>DetailsView Example in Asp.net</legend>    
        <asp:DetailsView ID="EmpDetailsView" runat="server" AllowPaging="True"
            AutoGenerateRows="False" Height="50px" Width="270px" CellPadding="4"
            onmodechanging="EmpDetailsView_ModeChanging"
            onpageindexchanging="EmpDetailsView_PageIndexChanging"
            onitemdeleting="EmpDetailsView_ItemDeleting"
            oniteminserting="EmpDetailsView_ItemInserting"
            onitemupdating="EmpDetailsView_ItemUpdating" DataKeyNames="Emp_Id"
            ForeColor="#333333" GridLines="None">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
            <EditRowStyle BackColor="#999999" />
            <EmptyDataTemplate>
                No Data<br />
                <asp:LinkButton ID="lnlAddNew" runat="server" CommandName="new">Add New</asp:LinkButton>
                <br />
                <br />
            </EmptyDataTemplate>
            <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
            <Fields>              
                <asp:TemplateField HeaderText="Id">
                    <ItemTemplate>
                        <asp:Label ID="lblId" runat="server" Text='<%# Eval("Emp_Id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Emp Name">
                <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Eval("EmpName") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEditName" runat="server" Text='<%# Eval("EmpName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <InsertItemTemplate>
                        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                    </InsertItemTemplate>                  
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Age">
                    <ItemTemplate>
                        <asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEditAge" runat="server" Text='<%# Eval("Age") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <InsertItemTemplate>
                        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
                    </InsertItemTemplate>                  
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Address">
                    <ItemTemplate>
                        <asp:Label ID="lblAddress" runat="server" Text='<%# Eval("Address") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEditAddress" runat="server" Text='<%# Eval("Address") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <InsertItemTemplate>
                        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
                    </InsertItemTemplate>                  
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Salary">
                    <ItemTemplate>
                        <asp:Label ID="lblSalry" runat="server" Text='<%# Eval("Salary") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEditSalary" runat="server" Text='<%# Eval("Salary") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <InsertItemTemplate>
                        <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
                    </InsertItemTemplate>                  
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lkNew" runat="server" CommandName="new">New</asp:LinkButton>
                        <asp:LinkButton ID="lkEdit" runat="server" CommandName="edit">Edit</asp:LinkButton>
                        <asp:LinkButton ID="lkDelete" runat="server" CommandName="delete">Delete</asp:LinkButton>
                     </ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton ID="lkEditUpdate" runat="server" CommandName="update">Update</asp:LinkButton>
                        <asp:LinkButton ID="lkEditCancel" runat="server" CommandName="cancel">Cancel</asp:LinkButton>
                    </EditItemTemplate>
                    <InsertItemTemplate>
                        <asp:LinkButton ID="lkInsert" runat="server" CommandName="insert">Insert</asp:LinkButton>
                        <asp:LinkButton ID="lkCancel" runat="server" CommandName="cancel">Cancel</asp:LinkButton>
                    </InsertItemTemplate>                  
                </asp:TemplateField>
            </Fields>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        </asp:DetailsView>
    </fieldset>

  </div>

4.       In the code behind file (.aspx.cs) write the code as: First of all include the following required namespaces and write the code:

using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;


SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constr"].ConnectionString);
      protected void Page_Load(object sender, EventArgs e)
      {
        if (Page.IsPostBack == false)
        {
            BindDetailView();
        }
    }
    private void BindDetailView()
    {
        SqlDataAdapter adp = new SqlDataAdapter();
        DataSet ds = new DataSet();
        try
        {
            adp = new SqlDataAdapter("SELECT * FROM Emp", con);
            adp.Fill(ds);
            if (ds.Tables[0].Rows.Count &gt; 0)
            {
                EmpDetailsView.DataSource = ds;
                EmpDetailsView.DataBind();
            }
            else
            {
                EmpDetailsView.DataSource = null;
                EmpDetailsView.DataBind();
            }
        }
        catch (Exception ex)
        {
            Response.Write("Oops!! Error occured: " + ex.Message.ToString());
        }
        finally
        {
            con.Close();
            ds.Dispose();
            adp.Dispose();
        }
    }
    protected void EmpDetailsView_ModeChanging(object sender, DetailsViewModeEventArgs e)
    {
        EmpDetailsView.ChangeMode(e.NewMode);
        BindDetailView();
    }
    protected void EmpDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        SqlCommand cmd = new SqlCommand();
        Int32 age;
        string ename = string.Empty;
        string addr = string.Empty;
        double sal;
        try
        {
            ename = ((TextBox)EmpDetailsView.Rows[1].FindControl("txtName")).Text;
            age = Convert.ToInt32(((TextBox)EmpDetailsView.Rows[2].FindControl("txtAge")).Text);
            addr = ((TextBox)EmpDetailsView.Rows[3].FindControl("txtAddress")).Text;
            sal = Convert.ToDouble(((TextBox)EmpDetailsView.Rows[4].FindControl("txtSalary")).Text);

            cmd = new SqlCommand(" INSERT INTO Emp(EmpName,Age,Address,Salary)VALUES(@ename,@age,@addr,@sal)", con);         
            cmd.Parameters.AddWithValue("@ename", ename);
            cmd.Parameters.AddWithValue("@age", age);
            cmd.Parameters.AddWithValue("@addr", addr);
            cmd.Parameters.AddWithValue("@sal", sal);
            con.Open();
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            EmpDetailsView.ChangeMode(DetailsViewMode.ReadOnly);
            BindDetailView();
        }
        catch (Exception ex)
        {
            Response.Write("Oops !! Error Occured: " + ex.Message.ToString());
        }
        finally
        {
            cmd.Dispose();
            con.Close();
            ename = string.Empty;
            addr = string.Empty;
        }
    }
    protected void EmpDetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        SqlCommand cmd = new SqlCommand();
        Int32 age;
        Int32 empId;
        string ename = string.Empty;
        string addr = string.Empty;
        double sal;
        try
        {
            ename = ((TextBox)EmpDetailsView.Rows[1].FindControl("txtEditName")).Text;
            age = Convert.ToInt32(((TextBox)EmpDetailsView.Rows[2].FindControl("txtEditAge")).Text);
            addr = ((TextBox)EmpDetailsView.Rows[3].FindControl("txtEditAddress")).Text;
            sal = Convert.ToDouble(((TextBox)EmpDetailsView.Rows[4].FindControl("txtEditSalary")).Text);

            cmd = new SqlCommand("UPDATE Emp SET EmpName=@ename,Age=@age,Address=@addr,Salary=@sal WHERE Emp_Id=@empId", con);
            //Read the Emp_id from the DataKeynames
            empId = Convert.ToInt32(EmpDetailsView.DataKey["Emp_Id"]);
            cmd.Parameters.AddWithValue("@empId", empId);
            cmd.Parameters.AddWithValue("@ename", ename);
            cmd.Parameters.AddWithValue("@age", age);
            cmd.Parameters.AddWithValue("@addr", addr);
            cmd.Parameters.AddWithValue("@sal", sal);
            con.Open();
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            EmpDetailsView.ChangeMode(DetailsViewMode.ReadOnly);
            BindDetailView();
        }
        catch (Exception ex)
        {
            Response.Write("Oops !! Error Occured: " + ex.Message.ToString());
        }
        finally
        {
            cmd.Dispose();
            con.Close();
            ename = string.Empty;
            addr = string.Empty;
        }
    }
    protected void EmpDetailsView_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
    {
        SqlCommand cmd = new SqlCommand();
        try
        {
            //Read the Emp_id from the DataKeynames
            Int32 empId = Convert.ToInt32(EmpDetailsView.DataKey["Emp_Id"]);
            cmd = new SqlCommand("DELETE FROM Emp WHERE Emp_Id=@EmpId", con);
            cmd.Parameters.Add("@EmpId", SqlDbType.Int).Value = empId;
            con.Open();
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            BindDetailView();
        }
        catch (Exception ex)
        {
            Response.Write("Oops !! Error Occured: " + ex.Message.ToString());
        }
        finally
        {
            con.Close();
            cmd.Dispose();
        }
    }
    protected void EmpDetailsView_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
    {
        EmpDetailsView.PageIndex = e.NewPageIndex;
        BindDetailView();
    }