Saturday, 23 May 2015

GridView Events Insert New, Edit, Delete in asp.net c#

In this poat I expalined Basic evnets of  GridView Like Insert, Edit and Update.

I have one gridview I need to write code to insert data into gridview after that I need to edit that gridview data and update it and if I want to delete the record in grdview we need to delete record simply by click on delete button of particular row to achieve these functionalities I have used some of gridview events those are


  1.  OnRowComand
  2.  OnRowEditing
  3.  OnRowCancelingEdit
  4.  OnRowUpdating
  5.  OnRowDeleting


First Here I writing a gridview code:-

.ASPX file:-

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: Title %>.</h2>
    <h3>Demp Application</h3>
    <p>Grid View:- Insert, Edit, Delete Events</p>
    <div>
<asp:GridView ID="EmpGridView" Width="700px" runat="server" AutoGenerateColumns="False"
    DataKeyNames="EmpId" onrowcancelingedit="EmpGridView_RowCancelingEdit" ShowFooter="True"
     onrowediting="EmpGridView_RowEditing" onrowdeleting="EmpGridView_RowDeleting"
            onrowupdating="EmpGridView_RowUpdating" onrowcommand="EmpGridView_RowCommand">  
    <Columns>
    <asp:TemplateField HeaderText="Edit" FooterStyle-HorizontalAlign="Center">
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/Images/update.gif"
    ToolTip="Update" Height="20px" Width="50px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/Exit.gif"
    ToolTip="Cancel" Height="20px" Width="50px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Images/Edit.png"
    ToolTip="Edit" Height="20px" Width="50px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server" ImageUrl="~/Images/delete.gif"
    ToolTip="Delete" Height="20px" Width="50px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/addnew.png" CommandName="AddNew" Width="90px"
     Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>

    <asp:TemplateField HeaderText="EmpId">
    <ItemTemplate>     <%#Eval("EmpId") %> </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Name">
    <ItemTemplate>    <%#Eval("EmpName") %></ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtEmpName" runat="server" Text='<%#Eval("EmpName") %>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
       <asp:TextBox ID="txtNewEmpName" runat="server"/>
         <asp:RequiredFieldValidator ID="empname" runat="server" ControlToValidate="txtNewEmpName"
             Text="*" ValidationGroup="validaiton" ForeColor="Red"/>
    </FooterTemplate>
    </asp:TemplateField>   
     <asp:TemplateField HeaderText="Salary">
     <ItemTemplate>    <%#Eval("EmpSalary") %>    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtEmpSalary" runat="server" Text='<%#Eval("EmpSalary") %>'></asp:TextBox>
    </EditItemTemplate>
         <FooterTemplate>
       <asp:TextBox ID="txtNewEmpSalary" runat="server"/>
         <asp:RequiredFieldValidator ID="empsalary" runat="server" ControlToValidate="txtNewEmpSalary"
             Text="*" ValidationGroup="validaiton" ForeColor="Red"/>
    </FooterTemplate>
    </asp:TemplateField>
     <asp:TemplateField HeaderText="Age">
    <ItemTemplate>    <%#Eval("Age") %> </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtAge" runat="server" Text='<%#Eval("Age") %>'></asp:TextBox>
    </EditItemTemplate>
          <FooterTemplate>
       <asp:TextBox ID="txtNewAge" runat="server"/>
         <asp:RequiredFieldValidator ID="empAge" runat="server" ControlToValidate="txtNewAge"
             Text="*" ValidationGroup="validaiton" ForeColor="Red"/>
    </FooterTemplate>
    </asp:TemplateField>
    </Columns>
    </asp:GridView>
    </div>
    <div>
        <asp:Label ID="lblresult" runat="server" Text=""></asp:Label>
    </div>

</asp:Content>

Design:-

















Explaination of GridView:-

AutoGenerateColumns: This property accepts only a Boolean value. The default value is true. When we set it to False that means the BoundField objects are  not created automatically; we will create the fields manually.

DataKeyNames: This property is used to associate a value with each row in the GridView. Here we can assign the name of a single database column or more than one column. When we assign more than one database columns then they are specified separated by commas. It represents datakey values. By this we uniquely identifiy records in GridView rows.

<Columns>: It is a collection of columns that the GridView contains. By this we can control what GridView columns are displayed, which means we can change the order of the appearance of the columns.

<asp:TemplateField>: Is used to add ASP.Net controls in GridView rows. One TemplateField represents one column in the GridView. It customizes the appearance of the UI in the GridView. It is useful when we are using a GridView to edit a database record.

<ItemTemplate>: It specifies the contents that are displayed in a TemplateField object. It displays a layout for the TemplateField.

<EditItemTemplate>: It also specifies contents that are displayed in a TemplateField but in EditMode.

Eval Function: It is a method that is used to display data. In this method we pass a database field name as an argument and that database field is displayed by this.

<asp:CommandField>: It is a special field that displays command buttons to perform selecting, editing, inserting and deleting.


.CS file:-

First i will set connection String and SQl-Connection
static String conStr = WebConfigurationManager.ConnectionStrings["TestWebCon"].ConnectionString.ToString();
        static SqlConnection con = new SqlConnection(conStr);


       // First time Bind GridView on Page Load
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bingGrid();
            }
        }


         // Bind method
        public void bingGrid()
        {

            SqlCommand cmd = new SqlCommand("[dbo].[getEmployee]", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                EmpGridView.DataSource = ds.Tables[0];
                EmpGridView.DataBind();

            }

            else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                EmpGridView.DataSource = ds.Tables[0];
                EmpGridView.DataBind();
                int columncount = EmpGridView.Rows[0].Cells.Count;
                EmpGridView.Rows[0].Cells.Clear();
                EmpGridView.Rows[0].Cells.Add(new TableCell());
                EmpGridView.Rows[0].Cells[0].ColumnSpan = columncount;
                EmpGridView.Rows[0].Cells[0].Text = "No Records Found";
                con.Close();
            }


        }

Event 1:- On this RowComand events I insert new record

        protected void EmpGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("AddNew"))
            {
                TextBox txtEmpName = (TextBox)EmpGridView.FooterRow.FindControl("txtNewEmpName");
                TextBox txtEmpSalary = (TextBox)EmpGridView.FooterRow.FindControl("txtNewEmpSalary");
                TextBox txtAge = (TextBox)EmpGridView.FooterRow.FindControl("txtNewAge");
                con.Open();
                SqlCommand cmd = new SqlCommand("[dbo].[InsertEmployee]", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@EmpName ", txtEmpName.Text);
                cmd.Parameters.AddWithValue("@EmpSalary ", txtEmpSalary.Text);
                cmd.Parameters.AddWithValue("@EmpAge ", txtAge.Text);
                //Sql Command Class method return effected rows use for insert,update, delete
                int result = cmd.ExecuteNonQuery();
                con.Close();
                if (result == 1)
                {
                    bingGrid();
                    lblresult.ForeColor = System.Drawing.Color.Green;
                    lblresult.Text = txtEmpName.Text + " Details inserted successfully";
                }
                else
                {
                    lblresult.ForeColor = System.Drawing.Color.Red;
                    lblresult.Text = txtEmpName.Text + " Details not inserted";
                }
            }
            


 ******  // If you want to update in side rowcommand event then this is the below code 

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
            {
              try
             {
              if (e.CommandName == "Edit")
              {
               ImageButton img = (ImageButton)e.CommandSource as ImageButton;
               GridViewRow row = img.NamingContainer as GridViewRow;

               TextBox2.Text = ((Label)row.FindControl("txtEditTimeDepart")).Text;
              }

             }
            catch (Exception ex)
            {
             lblstatus.Text = "Error" + ex.ToString();
             }
           }
      }


Event 2:- This event enable the editing in Gridview

protected void EmpGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            EmpGridView.EditIndex = e.NewEditIndex;
            bingGrid();//Fill GridView again call method
        }


 Event 3:- In this event you can cancel the editing
protected void EmpGridView_RowCancelingEdit(object sender,GridViewCancelEditEventArgs e)              {
            EmpGridView.EditIndex = -1;
            bingGrid();//Fill GridView again call method
        }
       

 Event 4:- This evnets allow you to save updates.
        protected void EmpGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //Get Each Row unique value from DataKeyNames
            int empid = Convert.ToInt32(EmpGridView.DataKeys[e.RowIndex].Value.ToString());
            //get TextBox Value in EditItemTemplet that row is clicked
            string name = ((TextBox)EmpGridView.Rows[e.RowIndex].FindControl("txtEmpName")).Text;
            string Salary = ((TextBox)EmpGridView.Rows[e.RowIndex].FindControl("txtEmpSalary")).Text;
            string Age = ((TextBox)EmpGridView.Rows[e.RowIndex].FindControl("txtAge")).Text;

            con.Open();
            SqlCommand cmd = new SqlCommand("[dbo].[UpdateEmpDetails]", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@EmpId ", empid);
            cmd.Parameters.AddWithValue("@EmpName ", name);
            cmd.Parameters.AddWithValue("@EmpSal ", Salary);
            cmd.Parameters.AddWithValue("@EmpAge ", Age);
            //Sql Command Class method return effected rows use for insert,update, delete
            cmd.ExecuteNonQuery();
            con.Close();
            // no row in edit mode
            EmpGridView.EditIndex = -1;
            //call method for agin fill grid after update
            lblresult.ForeColor = System.Drawing.Color.Green;
            lblresult.Text = " Details updated successfully";
            bingGrid();

        }


Event 5:- This evnet allow you to check the validation and delete record.
        protected void EmpGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int empid = Convert.ToInt32(EmpGridView.DataKeys[e.RowIndex].Value.ToString());
            con.Open();
            SqlCommand cmd = new SqlCommand("[dbo].[DeleteEmployee]", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@EmpId ", empid);
            cmd.ExecuteNonQuery();
            con.Close();
            lblresult.ForeColor = System.Drawing.Color.Green;
            lblresult.Text = " Details deleted successfully";
            bingGrid();
        }
    }



Now Let me create a table EmployeeMaster:-

CREATE TABLE [dbo].[tblEmpMaster](

[EmpID] [int] IDENTITY(1,1) NOT NULL,

[EmpName] [varchar](100) NOT NULL,

[EmpSalary] [int] NULL,

[Age] [int] NULL,

)

And Now I need to create Stored Procedures to Insert, Delete and Update data in above table

SP to Insert :-
CREATE Procedure [dbo].[InsertEmployee]
(
 @EmpName varchar(50),
 @EmpSalary int,
 @EmpAge int
 )

as
begin
declare @EmpID int=(Select isnull(max(EmpID),0)+from [dbo].[tblEmpMaster])

Insert into [dbo].[tblEmpMaster](EmpID,EmpName,EmpSalary,Age)
Values(@EmpID,@EmpName,@EmpSalary,@EmpAge)

end


SP to Delete :- 
Create Procedure [dbo].[DeleteEmployee]

(@EmpId varchar(50))

as
begin
Delete FROM [Employee].[dbo].[tblEmpMaster] where EmpID=@EmpId
end


CREATE Procedure [dbo].[getEmployee]

as
begin
SELECT [EmpID],[EmpName],[EmpSalary],[Age] FROM [Employee].[dbo].[tblEmpMaster]
end


SP to Update :- 
CREATE Procedure [dbo].[UpdateEmpDetails]

(@EmpId varchar(50),
 @empName varchar(50),
 @EmpSal int,
 @EmpAge int)

as 
begin 
update [Employee].[dbo].[tblEmpMaster]
set
EmpName=@EmpName,
EmpSalary=@empSal, 
Age=@EmpAge
where EmpID=@EmpId
end


Now finally let me run my app:-

1. There is no records found in Gridview see below:-










2. Let me Insert some records:-










3. And Let insert two more records and then will update the last record:-












See in the Image I added two more records and after that I Clicked on Edit button. For EmpId 's  3  I added last name as Singh.

4. See below after update the EmpId's 3  details











5. Now let Delete Second one record from gridView:-










See in above image Second record deleted from the gridView.


In the above article I try to explain the Events of GridView in asp.net c# with example. I hope its useful to you. Please
 post your feedback, question, or comments about this article.

No comments:

Post a Comment