Wednesday, 3 February 2016

asp .net How we insert update delete using grid view


First you copy paste design view on the page



 <h1 class="page-header">Add Category</h1>
 
    <label>Category Name</label>
    <asp:TextBox ID="txtcatname" runat="server" class="form-control"></asp:TextBox>

    <label>Category Image</label>
    <asp:FileUpload ID="FUPropImage" runat="server" CssClass="form-control" />
                                                    <asp:RegularExpressionValidator ID="rgvPropImage" runat="server" ControlToValidate="FUPropImage"
                                                        CssClass="red" Display="dynamic" ErrorMessage="<img src='../icon/error.png' width='12px' height='12px'/>"
                                                        ToolTip="Invalid Format!" ValidationExpression="^.+(.gif|.GIF|.jpg|.JPG|.png|.PNG|.tif|.TIF)$"
                                                        ValidationGroup="ENTRY"></asp:RegularExpressionValidator>
                                                    <strong class="textbox_content">&nbsp; Formats </strong><span style="color: orange">
                                                        .gif|.GIF|.jpg|.JPG|.png|.PNG|.tif|.TIF</span>
 
    <label>Category Detail</label>
    <asp:TextBox ID="txtcatdtl" textmode="MultiLine" runat="server" Height="150px" Width="100%" ></asp:TextBox>

    <label></label>

    <asp:Button ID="btnaddcat" runat="server" Text="ADD CATEGORY" class="btn btn-lg btn-primary btn-block" OnClick="btncat_Click" />
    <div class="panel">
         <h2 class="sub-header">Categories List</h2>
         <div class="table-responsive">
           
             <asp:GridView ID="GridView1" runat="server" ShowHeaderWhenEmpty="True"
            AutoGenerateColumns="False" onrowdeleting="RowDeleting"
            OnRowCancelingEdit="cancelRecord" OnRowEditing="editRecord"
            OnRowUpdating="updateRecord" CellPadding="4" GridLines="None" Width="100%"
            ForeColor="#333333" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="GridView1_PageIndexChanging" >
            <RowStyle BackColor="#E3EAEB" />
            <AlternatingRowStyle BackColor="White" />

            <Columns>

            <asp:TemplateField>
                <EditItemTemplate>
                    Cat
                </EditItemTemplate>
            <HeaderTemplate>Category Id</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID ="lblId" runat="server" Text='<%# Bind("CatID") %>'></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Category Name</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID ="lblcatName" runat="server" Text='<%# Bind("CatName") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
            <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("CatName") %>' MaxLength="50"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtName" runat="server" Text="*" ToolTip="Enter name" ControlToValidate="txtName"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revtxtName" runat="server" Text="*" ToolTip="Enter alphabate " ControlToValidate="txtName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$"></asp:RegularExpressionValidator>
         
            </EditItemTemplate>
            <FooterTemplate>
            <asp:TextBox ID="txtNewName" runat="server" MaxLength="50"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtNewName" runat="server" Text="*" ToolTip="Enter name" ControlToValidate="txtNewName"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revtxtNewName" runat="server" Text="*" ToolTip="Enter alphabate " ControlToValidate="txtNewName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$"></asp:RegularExpressionValidator>
       
            </FooterTemplate>
            </asp:TemplateField>
         
            <asp:TemplateField>
            <HeaderTemplate>Category Description</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID="lblcatdis" runat ="server" Text='<%# Bind("CatRemark") %>'></asp:Label>
            </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtcatre" runat="server" Text='<%# Bind("CatRemark") %>'></asp:TextBox>
                </EditItemTemplate>
            <FooterTemplate>
            <asp:TextBox ID="txtNewAge" runat="server"></asp:TextBox></FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Photo</HeaderTemplate>
            <ItemTemplate>
            <asp:Image ID="imgPhoto" Width="100px" Height="100px" runat="server" text="Photo" ImageUrl='<%# Bind("CatImage") %>' />
            </ItemTemplate>
            <EditItemTemplate>
            <asp:FileUpload ID="fuPhoto" runat="server" ToolTip="select Employee Photo"/>
            <asp:RegularExpressionValidator ID="revfuPhoto" runat="server" Text="*" ToolTip="Image formate only" ControlToValidate="fuPhoto" ValidationExpression="[a-zA-Z0_9].*\b(.jpeg|.JPEG|.jpg|.JPG|.jpe|.JPE|.png|.PNG|.mpp|.MPP|.gif|.GIF)\b"></asp:RegularExpressionValidator>
            </EditItemTemplate>
            <FooterTemplate>
            <asp:FileUpload ID="fuNewPhoto" runat="server" ToolTip="select Employee Photo"/>
            <asp:RequiredFieldValidator ID="rfvfuNewPhoto" runat="server" ErrorMessage="*" ToolTip="Select Photo" ControlToValidate="fuNewPhoto"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revfuNewPhoto" runat="server" Text="*" ToolTip="Image formate only" ControlToValidate="fuNewPhoto" ValidationExpression="[a-zA-Z0_9].*\b(.jpeg|.JPEG|.jpg|.JPG|.jpe|.JPE|.png|.PNG|.mpp|.MPP|.gif|.GIF)\b"></asp:RegularExpressionValidator>
            </FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Operation</HeaderTemplate>
            <ItemTemplate>
            <asp:Button ID="btnEdit" runat="server" CommandName="Edit" Text="Edit" OnClick="btnEdit_Click" />
            <asp:Button ID="btnDelete" runat="server" CommandName="Delete" Text="Delete" CausesValidation="true" OnClientClick="return confirm('Are you sure?')" OnClick="btnDelete_Click" />
            </ItemTemplate>
            <EditItemTemplate>
            <asp:Button ID="btnUpdate" runat="server" CommandName="Update" Text="Update" OnClick="btnUpdate_Click" />
            <asp:Button ID="btnCancel" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" OnClick="btnCancel_Click" />
            </EditItemTemplate>

            <FooterTemplate>
            <asp:Button ID="btnNewInsert" runat="server" Text="Insert" OnClick="InsertNewRecord"/>
            <asp:Button ID="btnNewCancel" runat="server" Text="Cancel" OnClick="AddNewCancel" CausesValidation="false" />
            </FooterTemplate>      
            </asp:TemplateField>        
            </Columns>
            <EditRowStyle BackColor="#7C6F57" />
            <EmptyDataTemplate>
                      No record available                  
            </EmptyDataTemplate>    
            <FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                 <PagerSettings FirstPageText="First" LastPageText="Last" NextPageText="Next" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />

        </asp:GridView>
         
     
    </div>
        </div>
    c# code


protected void cancelRecord(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        FillGridView();



    }
    protected void RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex].Delete();
            GlobalClass.adap.Update(GlobalClass.dt);
            // Get the image path for removing deleted's record image from server folder
            Image imgPhoto = GridView1.Rows[e.RowIndex].FindControl("imgPhoto") as Image;
            File.Delete(Server.MapPath(imgPhoto.ImageUrl));
            FillGridView();
        }
        catch
        {
            Response.Write("<script> alert('Sorry Category Not Deleted, Because It Has Sub-Category...') </script>");
        }

    }
    protected void editRecord(object sender, GridViewEditEventArgs e)
    {
     

        // Get the image path for remove old image after update record
        Image imgEditPhoto = GridView1.Rows[e.NewEditIndex].FindControl("imgPhoto") as Image;
        GlobalClass.imgEditPath = imgEditPhoto.ImageUrl;
        // Get the current row index for edit record
        GridView1.EditIndex = e.NewEditIndex;
        FillGridView();

    }
    protected void updateRecord(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            TextBox txtName = GridView1.Rows[e.RowIndex].FindControl("txtName") as TextBox;
            TextBox txtAge = GridView1.Rows[e.RowIndex].FindControl("txtcatre") as TextBox;
            FileUpload fuPhoto = GridView1.Rows[e.RowIndex].FindControl("fuPhoto") as FileUpload;
            Guid FileName = Guid.NewGuid();
            if (fuPhoto.FileName != "")
            {
                fuPhoto.SaveAs(Server.MapPath("~/proimage/img/" + FileName + ".png"));
                GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["CatImage"] = "~/proimage/img/" + FileName + ".png";
                File.Delete(Server.MapPath(GlobalClass.imgEditPath));
            }
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["CatName"] = txtName.Text.Trim();
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["CatRemark"] =txtAge.Text.Trim();
            GlobalClass.adap.Update(GlobalClass.dt);
            GridView1.EditIndex = -1;
            Response.Write("<script> alert('Record updated Successfully...') </script>");
            FillGridView();
        }
        catch
        {
            Response.Write("<script> alert('Record updation fail...') </script>");
        }
     

    }
    protected void btncat_Click(object sender, EventArgs e)
    {
      try{
        Guid FileName = Guid.NewGuid();
        FUPropImage.SaveAs(Server.MapPath("~/proimage/img/" + FileName + ".png"));
        DataRow dr = GlobalClass.dt.NewRow();
        dr["CatName"] = txtcatname.Text.Trim();
        dr["CatRemark"] = txtcatdtl.Text;
        dr["RegDate"] = DateTime.Now.ToString("mm/dd/yyyy HH:mm:ss");
        dr["Active"] ="True";

        dr["CatImage"] = "~/proimage/img/" + FileName + ".png";
        GlobalClass.dt.Rows.Add(dr);
        GlobalClass.adap.Update(GlobalClass.dt);
     
        FillGridView();
        Response.Write("<script> alert('Category Added Successfully!!!') </script>");
     
    }
        catch
        {
            Response.Write("<script> alert('Sorry Category Not Added or Already Exist...') </script>");
        }



        }

    public string GetUniqueFileName(string filename)
    {
        try
        {
            string[] ext = new string[5];
            ext = filename.Split('.');
            return ext[0] + Guid.NewGuid().ToString() + "." + ext[ext.Length - 1];
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

    public void FillGridView()
    {
        try
        {

            string cnString = ConfigurationManager.ConnectionStrings["cons"].ConnectionString;
            SqlConnection con = new SqlConnection(cnString);
            GlobalClass.adap = new SqlDataAdapter("select * from Categories", con);
            SqlCommandBuilder bui = new SqlCommandBuilder(GlobalClass.adap);
            GlobalClass.dt = new DataTable();
            GlobalClass.adap.Fill(GlobalClass.dt);
            GridView1.DataSource = GlobalClass.dt;
            GridView1.DataBind();
        }
        catch
        {
            Response.Write("<script> alert('Connection String Error...') </script>");
        }
    }


call fillgrid method in pageload event