Skip to main content

Deleting Row option with deleting file from server and database through gridview

First use gridview :

 <asp:GridView ID="grdAcademicResourceFilesView" runat="server" AutoGenerateColumns="False"
                            CellPadding="4" DataKeyNames="ID" ForeColor="#333333" GridLines="None" OnRowDeleting="grdAcademicResourceFilesView_RowDeleting"
                            Width="100%">
                            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                            <Columns>
                                <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
                                <asp:BoundField DataField="Name" HeaderText="Category Name" SortExpression="Name" />
                                <asp:BoundField DataField="ProgramCode" HeaderText="Program Code" SortExpression="ProgramCode" />
                                <asp:BoundField DataField="Semester" DataFormatString="Semester {0}" HeaderText="Term Id"
                                    SortExpression="Semester" />
                                <asp:BoundField DataField="UploadedFileName" HeaderText="File Name" SortExpression="UploadedFileName" />
                                <asp:BoundField DataField="CreatedBy" HeaderText="Uploaded By" SortExpression="CreatedBy" />
                                <asp:BoundField DataField="CreatedDate" DataFormatString="{0:d}" HeaderText="Upload Date"
                                    SortExpression="CreatedDate" />
                                <asp:BoundField DataField="CourseCode" HeaderText="Course Code" SortExpression="CourseCode" />
                                <asp:BoundField DataField="Remarks" HeaderText="Remarks" SortExpression="Remarks" />
                                <asp:TemplateField ShowHeader="False">
                                    <ItemTemplate>
                                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
                                            OnClientClick="return confirm ('Are you sure to delete this record');" Text="Delete"></asp:LinkButton>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                            <EditRowStyle BackColor="#999999" />
                            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                        </asp:GridView>

Then add sqldata source to attach to it.
 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:LCODLConnectionString %>"
                            SelectCommand="LcOdlViewAcademicUploadedFiles" SelectCommandType="StoredProcedure"></asp:SqlDataSource>

Then create event of gridview ROW DELETING and paste following code in code behind model

  protected void grdAcademicResourceFilesView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string rowID = Convert.ToString(grdAcademicResourceFilesView.DataKeys[e.RowIndex]["ID"]);
        string uploadedFileName = grdAcademicResourceFilesView.Rows[e.RowIndex].Cells[4].Text;
        if (!string.IsNullOrEmpty(uploadedFileName))
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LCODLConnectionString"].ConnectionString))
            {
                SqlTransaction tran = null;
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                tran = con.BeginTransaction();
                bool canDeleteFile = false;
                try
                {
                    SqlParameter[] param = new SqlParameter[2];
                    param[0] = new SqlParameter("@id", rowID);
                    param[1] = new SqlParameter("@canDelete", SqlDbType.Bit);
                    param[1].Direction = ParameterDirection.Output;
                    SqlHelper.ExecuteNonQuery(tran, CommandType.StoredProcedure, "LcOdlDeleteUploadedAcademicFile", param);
                    canDeleteFile = Convert.ToBoolean(param[1].Value);
                    tran.Commit();
                }
                catch (SqlException ex)
                {
                    tran.Rollback();
                    ScriptManager.RegisterStartupScript(grdAcademicResourceFilesView, grdAcademicResourceFilesView.GetType(), "DeletingError", "alert('Some thing went wrong while deleting file. Please try again later');", true);
                    return;
                }
                finally
                {
                    con.Close();
                }
                //Now going To Deleet file from filesystem

                string Rootfolder = Server.MapPath("~/IpSyllabusSchemas");
                string FilePathWithName = string.Format("{0}\\{1}", Rootfolder, uploadedFileName);
                if (canDeleteFile)
                {
                    if (File.Exists(FilePathWithName))
                    {
                        try
                        {
                            File.Delete(FilePathWithName);
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            ScriptManager.RegisterStartupScript(grdAcademicResourceFilesView, grdAcademicResourceFilesView.GetType(), "DeletingError", "alert('Some thing went wrong while deleting file. Please try again later');", true);
                            return;
                        }
                    }
                }

                grdAcademicResourceFilesView.DataSource = GetUploadedFiles();
                grdAcademicResourceFilesView.DataBind();
            }

        }
    }

Done :)

Comments

Popular posts from this blog

Snake Xenzia

Hello friends did you remember the GAME you play on nokia 1100 , SNAKE XENZIA .Yeah the same you are thinking ,a snake eating food and go longer and longer till it dies. Why to play it on mobile when it is available on your pc ??? It is made in .net framework 4.0 .Just install the setup and play SNAKE XENZIA . Have Fun !! DOWNLOAD IT   HERE  . Related articles Rattlesnake Dreams "Classsic Snake Game In C"? Resident Evil 6 gamescom demo takes in a giant snake battle Snakes & ladders

Export Doc,Access,Image,CSV,Excel,Pdf,XML,HTML,Text,Print of Gridview in Asp.net

First import itextsharp.dll in the solution and use three namespces (basically for pdf) using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.html.simpleparser;          Then Use the following code :- on each button  click  protected void Page_Load(object sender, EventArgs e)         {             if (!Page.IsPostBack)             {                 BindGridDetails(GridView1);             }         }                 protected DataTable BindGridDetails(GridView GridView1)         {   ...

ZORIN OS FOR WINDOWS USERS

Download(FREE) Zorin OS 6 - Best Linux Distro For Windows User As the dawn of the  Windows 8  era approaches, there are more reasons than ever for longtime Windows users to consider  switching to Linux . Making that switch has never been easier thanks to supremely user-friendly options like  Ubuntu Linux  and Linux Mint , but there's also a lesser-known Linux flavor that's designed specifically to offer an easy transition from Microsoft's operating system. Zorin OS is an Ubuntu-based Linux distribution that actually bills itself as “the gateway to Linux for Windows users.” I wrote about the free and open source operating system once  back in 2010 , but just this week a brand-new version 6 made its debut. If you're accustomed to Windows but are feeling anxious about Windows 8 and all the changes it will bring--or if you're a Linux user who's dissatisfied with the current crop of  desktops  out there--Zorin OS 6 could be just wh...