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

2 comments: