Friday 21 December 2012

Java Script for GridView Pager

Java Script for GridView Pager


<script src='<%=Page.ResolveUrl("~/Scripts/tablesorter.js") %>' type="text/javascript"></script>
     <script src='<%=Page.ResolveUrl("~/Scripts/jquery.tablesorter.pager.js") %>' type="text/javascript"></script>



<script type="text/javascript">

    $(document).ready(function () {
        var rowsCount = '<%=Grid_Subscription.Rows.Count %>';
        var s = document.getElementById('<%= Grid_Subscription.ClientID %>');
        $("#" + s.id.toString()).tablesorter({ sortList: [[0, 0]], headers: { 6: { sorter: false }, 7: { sorter: false }, 8: { sorter: false}} }).tablePagination({ optionsForRows: [10, 25, 50, 100, rowsCount] });
    });
</script>

Tuesday 4 December 2012

Javascript Validation of Numeric,Phone,Albhabet,Date

Javascript Validation of Numeric,Phone,Albhabet,Date

<html>
<head><title>Javascript validation</title>

<script language="javascript" type="text/javascript">
        function isCurrency(evt, txtid) {
            var charCode = (evt.which) ? evt.which : event.keyCode
            var ctrl = document.getElementById(txtid)
            if (ctrl.value.indexOf('.') == -1 && charCode == 46)
                true;
            else if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                alert(" you can enter Only Numeric character..!!!");
                return false;
            }
            return true;
        }
        function CheckDate(sender, args) {
            if (sender._selectedDate > new Date()) {
                alert("Please Select Valid Birth Date...!!");
                sender._selectedDate = new Date();
                sender._textbox.set_Value(sender._selectedDate.format(sender._format));
            }
        }
        function OnlyAlphabets(evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode
            if ((charCode >= 97 && charCode <= 122) || (charCode >= 65 && charCode <= 90) || (charCode <= 32))
                true;
            else {
                alert("Only Alhaphet Characters Are Allowed To Enter..!!!");
                return false;
            }
            return true;
        }

        function DisableButton(buttonElem) {
            buttonElem.value = "Please Wait....";
            buttonElem.disabled = true;

        }
        function isName(evt, txtid) {
            var charCode = (evt.which) ? evt.which : event.keyCode
            var ctrl = document.getElementById(txtid)
            if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || (charCode == 32) || (charCode == 46)) {
                return true;
            }
            else
                alert("You Can Enter Only Alphabets,Space,Or Dot(.)");
            return false;
        }
        function isNumberKey(evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode
            if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                alert("you can enter Only Numeric character..!!!");
                return false;
            }
            return true;
        }
        function isPhoneNo(evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode
            if (charCode == 45) return true;
            if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                alert("you can enter Only Numeric characters and '-' ...!!!");
                return false;
            }
            return true;
        }

        function NoNumberKey(evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode
            if (charCode >= 48 && charCode <= 57) {
                alert("Digits are not allowed..!!!");
                return false;
            }
            return true;
        }

    </script>
</head>
<body>
<form id="from1" runat="server">
<div>
<table>
<tr>
<td>User Name:</td>
<td>
 <asp:TextBox ID="txt_username" runat="server" CssClass="txt" MaxLength="10"
  onkeypress="return OnlyAlphabets(evt);" Width="116px"></asp:TextBox>
</td>
</tr>
<tr>
<td>Mobile:</td>
<td>
 <asp:TextBox ID="txt_Mobile" runat="server" CssClass="txt" MaxLength="10"
  onkeypress="return isNumberKey(event);" Width="116px"></asp:TextBox>
</td>
</tr>
</div>
</form>
</body>
</html>

Select DOB from dropdownlist Year,Month,Date

Select DOB from dropdownlist Year,Month,Date


<asp:UpdatePanel ID="updatepanel2" runat="server">
        <ContentTemplate>
        <asp:DropDownList ID="ddlBirthyear" runat="server" AutoPostBack="True" ToolTip="Select Year" TabIndex="13"
                                            onselectedindexchanged="ddlBirthyear_SelectedIndexChanged">
                                              <asp:ListItem Text="-- Year --" Value=""> </asp:ListItem>
                                        </asp:DropDownList>
                                        <asp:DropDownList ID="ddlBirthmonth" runat="server" AutoPostBack="True" ToolTip="Select Month" TabIndex="14"
                                            onselectedindexchanged="ddlBirthmonth_SelectedIndexChanged">
                                              <asp:ListItem Text="-- Month --" Value=""> </asp:ListItem>
                                        </asp:DropDownList>
                                         <asp:DropDownList ID="ddlBirthdate" runat="server" ToolTip="Select Date" TabIndex="15" >
                                          <asp:ListItem Text="-- Date --" Value=""> </asp:ListItem>
                                        </asp:DropDownList>
        </ContentTemplate>
        </asp:UpdatePanel>

.cs code

 protected void Page_Load(object sender, EventArgs e)
    {
        #region DOB DDL

        for (int i = 1; i <= 31; i++)
        {
            ddlBirthdate.Items.Add(i.ToString());
        }

        int[] n = (int[])Enum.GetValues(typeof(Month));

        foreach (int x in n)
        {
            ddlBirthmonth.Items.Add(new ListItem(Enum.Parse(typeof(Month), x.ToString()).ToString(), x.ToString()));
        }


        //for (int i = 1; i <= 12; i++)
        //{

        //    ddlBirthmonth.Items.Add(i.ToString());
        //}
        for (int i = DateTime.Now.Year; i >= 1960; i--)
        {
            ddlBirthyear.Items.Add(i.ToString());
        }

        #endregion
    }

    #region  DDL DOB - Binds Drop down for date of birth

    public enum Month
    {
        January = 1,
        February = 2,
        March = 3,
        April = 4,
        May = 5,
        June = 6,
        July = 7,
        August = 8,
        September = 9,
        October = 10,
        November = 11,
        December = 12
    }

    private bool CheckLeap(int year)
    {
        if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
            return true;
        else
            return false;
    }

    private void BindDays(int year, int month)
    {
        int i;
        System.Collections.ArrayList AlDay = new System.Collections.ArrayList();

        switch (month)
        {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                for (i = 1; i <= 31; i++)
                    AlDay.Add(i);
                break;
            case 2:
                if (CheckLeap(year))
                {
                    for (i = 1; i <= 29; i++)
                        AlDay.Add(i);
                }
                else
                {
                    for (i = 1; i <= 28; i++)
                        AlDay.Add(i);
                }
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                for (i = 1; i <= 30; i++)
                    AlDay.Add(i);
                break;
        }

        ddlBirthdate.DataSource = AlDay;
        ddlBirthdate.DataBind();
        ddlBirthdate.Items.Insert(0, new ListItem("-- Date --"));

    }

    protected void ddlBirthyear_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlBirthyear.SelectedIndex != 0)
        {
            int year = Int32.Parse(ddlBirthyear.SelectedValue);
            int month = 1;
            try { month = Int32.Parse(ddlBirthmonth.SelectedValue); }
            catch { }
            BindDays(year, month);
        }
        else
        {
            ddlBirthdate.SelectedIndex = 0;
        }

    }

    protected void ddlBirthmonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlBirthmonth.SelectedIndex != 0)
        {
            int year = 2000;
            try { year = Int32.Parse(ddlBirthyear.SelectedValue); }
            catch { }
            int month = Int32.Parse(ddlBirthmonth.SelectedValue);
            BindDays(year, month);
        }
        else
        {
            ddlBirthdate.SelectedIndex = 0;

        }
    }

    #endregion
  
    protected void btnsave_Click(object sender, EventArgs e)
    {
        String DOB = ddlBirthdate.SelectedItem.Text + "/" + ddlBirthmonth.SelectedValue + "/" + ddlBirthyear.SelectedValue;
    }
}

Sunday 2 December 2012

Mail sending code with Cc, Bcc and multiple dynamic File Attachments

Mail sending code with Cc, Bcc and multiple dynamic File Attachments


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<script type = "text/javascript">
    var counter = 0;
    function AddFileUpload() {
        var div = document.createElement('DIV');
        div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +
                     '" type="file" />' +
                     '<input id="Button' + counter + '" type="button" ' +
                     'value="Remove" onclick = "RemoveFileUpload(this)" />';
        document.getElementById("FileUploadContainer").appendChild(div);
        counter++;
    }
    function RemoveFileUpload(div) {
        document.getElementById("FileUploadContainer").removeChild(div.parentNode);
    }
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div>
<br />
<table>
<tr>
<td style="width:25px">&nbsp;</td>
    <td>
        To</td>
    <td><asp:TextBox ID="txtto" runat="server" Width="250px" Height="22px"></asp:TextBox></td>
</tr>
<tr>
<td style="width:25px">&nbsp;</td>
    <td>
        CC</td>
    <td><asp:TextBox ID="txtcc" runat="server" Width="250px" Height="22px"></asp:TextBox></td>
</tr>
<tr>
<td style="width:25px">&nbsp;</td>
    <td>
        BCC</td>
    <td><asp:TextBox ID="txtbcc" runat="server" Width="250px" Height="22px"></asp:TextBox></td>
</tr>
<tr>
<td>&nbsp;</td>
    <td>
        Subject</td>
    <td><asp:TextBox ID="txtsubject" runat="server" Width="250px"
            ontextchanged="txtsubject_TextChanged"></asp:TextBox></td>
</tr>
<tr>
<td>&nbsp;</td>
    <td>
        &nbsp;</td>
        <td>
       
            <span style ="font-family:Arial">Click to add files</span>&nbsp;&nbsp;
    <input id="Button1" type="button" value="add" onclick = "AddFileUpload();" />
    <br /><br />
    <div id = "FileUploadContainer">
        <asp:FileUpload ID="fileUpload1" runat="server" />
    </div>
    <br />
        </td>

</tr>
<tr>
<td>&nbsp;</td>
    <td>
        Message</td>
    <td><asp:TextBox ID="txtmessage" runat="server" Width="350px" TextMode="MultiLine" Height="60px"></asp:TextBox></td>
</tr>
<tr>
<td>&nbsp;</td>
    <td colspan="2">
        <asp:Label ID="lblmsg" runat="server" Text=""></asp:Label>
    </td>
</tr>
<tr>
<td>
    &nbsp;</td>
    <td colspan="2">
        <center>
            <asp:Button ID="bensave" runat="server" onclick="bensave_Click" Text="Send" />
        </center>
    </td>
</tr>
</table>
</div>
    </div>
    </form>
</body>
</html>

Web.Config Configurations

<httpRuntime
  executionTimeout="110"
  maxRequestLength="4096"
  requestLengthDiskThreshold="80"
  useFullyQualifiedRedirectUrl="false"
  minFreeThreads="8"
  minLocalRequestFreeThreads="4"
  appRequestQueueLimit="5000"
  enableKernelOutputCache="true"
  enableVersionHeader="true"
  requireRootedSaveAsPath="true"
  enable="true"
  shutdownTimeout="90"
  delayNotificationTimeout="5"
  waitChangeNotification="0"
  maxWaitChangeNotification="0"
  enableHeaderChecking="true"
  sendCacheControlHeader="true"
  apartmentThreading="false"
/>

.cs Code

 protected void bensave_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(txtto.Text);
        if(txtcc.Text.Trim().Length!=0)
        {
            mail.CC.Add(txtcc.Text);
        }
        if (txtbcc.Text.Trim().Length != 0)
        {
            mail.Bcc.Add(txtbcc.Text);
        }
        mail.From = new MailAddress("salikrammaurya@gmail.com");
        mail.Subject = txtsubject.Text;
        mail.Body = txtmessage.Text;
        mail.IsBodyHtml = true;

        if (fileUpload1.HasFile)
        {
         

            for (int i = 0; i < Request.Files.Count; i++)
            {
                mail.Attachments.Add(new Attachment(fileUpload1.PostedFile.InputStream, fileUpload1.FileName));
             
            }

        }
 
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
        smtp.Credentials = new System.Net.NetworkCredential("salikrammaurya@gmail.com", "password");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = true;
        smtp.Send(mail);
        lblmsg.Text = "Mail send successfully";
        clear();

    }
    public void clear()
    {
        txtto.Text = txtsubject.Text = txtmessage.Text = txtcc.Text = txtbcc.Text = string.Empty;
    }

Wednesday 28 November 2012

Export data in PDF formate form GridView

        Export data in PDF formate form GridView

     void ExportPDF1()
     {
        GridView grdview1 = new GridView();
        CssClass_GridView(grdview1);
        SqlConnection conn = new SqlConnection(con);
        SqlCommand cmd = new SqlCommand("fetchDataForReportnew", conn);
        cmd.Parameters.AddWithValue("@empid", Convert.ToInt64(Session["EmpId"]));
        cmd.Parameters.AddWithValue("@Curr_Emp", Session["UserName"].ToString());
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        Document pdfDoc = new Document(PageSize.A4, 9f, 9f, 9f, 0f);
        System.IO.MemoryStream msReport = new System.IO.MemoryStream();

        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, msReport);

        if (dt.Rows.Count > 0)
        {
            grdview1.DataSource = dt;
            grdview1.DataBind();
        }
        StringWriter sw0 = new StringWriter();
        HtmlTextWriter hw0 = new HtmlTextWriter(sw0);
        if (grdview1 != null && grdview1.Rows.Count > 0)
        {

            string filename = Session["UserName"].ToString() + "_Expense_" + DateTime.Now.Ticks + ".pdf";
            string file_Path = "~\\ExportFiles\\" + filename;
            PdfWriter.GetInstance(pdfDoc, new FileStream(Server.MapPath(file_Path), FileMode.Create));
            pdfDoc.Open();

            PdfPTable table = new PdfPTable(6);
            table.TotalWidth = 578f;
            table.LockedWidth = true;
            PdfPCell Header1 = new PdfPCell(new Phrase("Travel Record", FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.NORMAL)));
            Header1.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell Header2 = new PdfPCell(new Phrase("DATE OF REQUISITION", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL)));
            Header1.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell name = new PdfPCell(new Phrase(dt.Rows[0]["Requisition Date"].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.NORMAL)));
            name.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell territory = new PdfPCell(new Phrase("NAME", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL)));
            territory.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell terriname = new PdfPCell(new Phrase(dt.Rows[0]["Employee"].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.NORMAL)));
            terriname.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell submitdate = new PdfPCell(new Phrase("TERRITORY", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL)));
            territory.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell date_submit = new PdfPCell(new Phrase(dt.Rows[0]["Branch"].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.NORMAL)));
            terriname.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell Date = new PdfPCell(new Phrase("From", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.WHITE)));
            Date.BackgroundColor = new Color(80, 124, 209);
            Date.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell AreaVisited = new PdfPCell(new Phrase("To", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.WHITE)));
            AreaVisited.BackgroundColor = new Color(80, 124, 209);
            AreaVisited.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell CustomerName = new PdfPCell(new Phrase("Departure Date", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.WHITE)));
            CustomerName.BackgroundColor = new Color(80, 124, 209);
            CustomerName.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell Product = new PdfPCell(new Phrase("Mode Of Travel", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.WHITE)));
            Product.BackgroundColor = new Color(80, 124, 209);
            Product.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell Purpose = new PdfPCell(new Phrase("Purpose of visit", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.WHITE)));
            Purpose.BackgroundColor = new Color(80, 124, 209);
            Purpose.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell mode = new PdfPCell(new Phrase("Fare",FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.WHITE)));
            mode.BackgroundColor = new Color(80, 124, 209);
            mode.HorizontalAlignment = Element.ALIGN_CENTER;

            Header1.Colspan = 6;
            table.AddCell(Header1);
            Header2.Colspan = 2;
            table.AddCell(Header2);
            name.Colspan = 4;
            name.HorizontalAlignment = Element.ALIGN_LEFT;
            table.AddCell(name);
            territory.Colspan = 2;
            territory.HorizontalAlignment = Element.ALIGN_LEFT;
            table.AddCell(territory);
            terriname.Colspan = 4;
            terriname.HorizontalAlignment = Element.ALIGN_LEFT;
            table.AddCell(terriname);
            submitdate.Colspan = 2;
            submitdate.HorizontalAlignment = Element.ALIGN_LEFT;
            table.AddCell(submitdate);
            date_submit.Colspan = 4;
            date_submit.HorizontalAlignment = Element.ALIGN_LEFT;
            table.AddCell(date_submit);
            table.AddCell(Date);
            table.AddCell(AreaVisited);
            table.AddCell(CustomerName);
            table.AddCell(Product);
            table.AddCell(Purpose);
            table.AddCell(mode);
           

            pdfDoc.Add(table);
            iTextSharp.text.Table datatable = new iTextSharp.text.Table(6);
            datatable.Width = 100f;
            datatable.Padding = 1;
            datatable.Border = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {

                Chunk dateofvisit = new Chunk(dt.Rows[i]["From Location"].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.NORMAL));
                Cell date = new Cell(dateofvisit);
               
                date.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(date);
                Chunk area_visited = new Chunk(dt.Rows[i]["To Location"].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.NORMAL));
                Cell areavisited = new Cell(area_visited);
                areavisited.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(areavisited);
                Chunk customer_name = new Chunk(dt.Rows[i]["DateOfVisit"].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.NORMAL));
                Cell customername = new Cell(customer_name);
                customername.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(customername);
                Chunk product = new Chunk(dt.Rows[i]["ModeOfTravel"].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.NORMAL));
                Cell product1 = new Cell(product);
                product1.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(product1);
                Chunk purpose = new Chunk(dt.Rows[i]["Purpose Of Visit"].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.NORMAL));
                Cell purpose1 = new Cell(purpose);
                purpose1.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(purpose1);
                Chunk chunk = new Chunk(dt.Rows[i]["Fare"].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.NORMAL));
                Cell cell = new Cell(chunk);
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                datatable.AddCell(cell);
            }

            decimal grdtotal = 0;
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                string gd = dt.Rows[r]["Fare"].ToString();
                if (gd != "")
                    grdtotal += Convert.ToDecimal(gd);
            }
         
            Chunk Gtotal2 = new Chunk("Grand Total (Rs.)", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD));
            Cell Grand_total12 = new Cell(Gtotal2);
            Grand_total12.Colspan = 5;
            Grand_total12.HorizontalAlignment = Element.ALIGN_RIGHT;
            datatable.AddCell(Grand_total12);

            Chunk Gtotal1 = new Chunk(grdtotal.ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.NORMAL));
            Cell Grand_total = new Cell(Gtotal1);
            Grand_total.HorizontalAlignment = Element.ALIGN_CENTER;
            datatable.AddCell(Grand_total);

            pdfDoc.Add(datatable);
            Session["file_name"] = filename;
            Session["file_path"] = file_Path;
            Session["type"] = "Travel";
            pdfDoc.Close();
}

Export data from Gridview to Excel in Asp.net

Export data from Gridview to Excel in Asp.net

protected void btnexport_Click(object sender, EventArgs e)
    {
        //first method
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=GridView_to_Excel.xls");   
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter StringWriter = new System.IO.StringWriter();
        HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);
        grdview.Columns.RemoveAt(6);
        grdview.RenderControl(HtmlTextWriter);
        Response.Write(StringWriter.ToString());
        Response.End();

      //second method

    ////    dbconnect ob = new dbconnect();
    ////    int colIndex = 1;
    ////    int rowIndex = 1;
    ////    Excel.Application xlApp;
    ////    Excel.Workbook xlWorkBook;
    ////    Excel.Worksheet xlWorkSheet;
    ////    object misValue = System.Reflection.Missing.Value;
    ////    xlApp = new Excel.Application();
    ////    Excel.Range ExelRange;
   
    ////    DataTable dt = new DataTable();
    ////    dt = ob.Gridbind();

    ////    xlApp = new Excel.Application();
    ////    xlWorkBook = xlApp.Workbooks.Add(misValue);
    ////    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

    ////    foreach (DataRow theRow in dt.Rows)
    ////    {
    ////        rowIndex = rowIndex + 1;
    ////        colIndex = 0;
    ////        foreach (DataColumn dc in dt.Columns)
    ////        {
    ////            colIndex = colIndex + 1;
    ////            xlWorkSheet.Cells[rowIndex + 1, colIndex] = theRow[dc.ColumnName];
    ////            xlWorkSheet.Rows.AutoFit();
    ////            xlWorkSheet.Columns.AutoFit();
    ////        }
    ////    }

    ////    xlWorkSheet.get_Range("b2", "e2").Merge(false);

    ////    ExelRange = xlWorkSheet.get_Range("b2", "e2");
    ////    ExelRange.FormulaR1C1 = "Exel Title or Table Name ";

    ////    ExelRange.HorizontalAlignment = 3;
    ////    ExelRange.VerticalAlignment = 3;

    ////    xlApp.Visible = true;
    ////    ObjectRelease(xlWorkSheet);
    ////    ObjectRelease(xlWorkBook);
    ////    ObjectRelease(xlApp);



    ////}

    ////private void ObjectRelease(object objRealease)
    ////{
    ////try
    ////{
    ////    System.Runtime.InteropServices.Marshal.ReleaseComObject(objRealease);
    ////    objRealease = null;
    ////}
    ////catch (Exception ex)
    ////{
    ////    objRealease = null;
      
    ////}
    ////finally
    ////{
    ////    GC.Collect();
    ////}
    }


    public override void VerifyRenderingInServerForm(Control control)
    {

        /* Verifies that the control is rendered */

    }
  

Tuesday 6 November 2012

Sending Email in Asp.net with Attachment and without Attachment


1)without attachment
.aspx code

<html>
<head></head>
<body>
<div>
<br />
<table>
<tr>
<td>To</td><td><asp:TextBox ID="txtto" runat="server" Width="200px"></asp:TextBox></td>
</tr>
<tr>
<td>Subject</td><td><asp:TextBox ID="txtsubject" runat="server" Width="250px"></asp:TextBox></td>
</tr>
<tr>
<td>Message</td><td><asp:TextBox ID="txtmessage" runat="server" Width="350px" TextMode="MultiLine" Height="60px"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2"><asp:Label ID="lblmsg" runat="server" Text=""></asp:Label></td>
</tr>
<tr>
<td colspan="2">
<center>
<asp:Button ID="bensave" runat="server" Text="Send" onclick="bensave_Click" />
</center>
</td>
</tr>
</table>
</div>
</body>
</html>

.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void bensave_Click(object sender, EventArgs e)
    {
        var mail = new MailMessage();
        mail.From = new MailAddress("salikrammaurya@gmail.com");
        mail.To.Add(txtto.Text);
        mail.Subject = txtsubject.Text;
        mail.IsBodyHtml = true;
        mail.Body =txtmessage.Text;
        mail.Priority = MailPriority.High;
        var mailClient = new SmtpClient("smtp.gmail.com", 587);
        mailClient.EnableSsl = true;
        mailClient.Credentials = new System.Net.NetworkCredential("salikrammaurya@gmail.com", "password");
        mailClient.Send(mail);
        lblmsg.Text = "Mail sent successfully!";
        txtto.Text = txtsubject.Text = txtmessage.Text = string.Empty;
    }
}

2) With Attachment

.aspx code

<html>
<head></head>
<body>
<div>
<table style=" border:1px solid" align="center">
<tr>
<td colspan="2" align="center">
<b>Send Mail with multiple Attachments using asp.net</b>
</td>
</tr>
<tr>
<td>To</td><td><asp:TextBox  ID="txtto" runat="server" Width="200px" ></asp:TextBox></td>
</tr>
<tr>
<td>Subject</td><td><asp:TextBox  ID="txtsubject" runat="server" Width="200px" ></asp:TextBox></td>
</tr>
<tr>
<td>Message</td><td><asp:TextBox  ID="txtmessage" runat="server" Width="200px" TextMode="MultiLine" ></asp:TextBox></td>
</tr>
<tr>
<td>
Attach a file:
</td>
<td>
<asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:FileUpload ID="fileUpload2" runat="server" /><br />
<asp:FileUpload ID="fileUpload3" runat="server" /><br />
<asp:FileUpload ID="fileUpload4" runat="server" /><br />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" Text="Send" runat="server" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
</body>
</html>

.cs code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Linq;
using System.Net.Mail;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        MailMessage mail = new MailMessage();
        mail.To.Add(txtto.Text);
        mail.From = new MailAddress("salikrammaurya@gmail.com");
        mail.Subject = txtsubject.Text;
        mail.Body = txtmessage.Text;
        mail.IsBodyHtml = true;

        //Attach file using FileUpload Control and put the file in memory stream
        if (fileUpload1.HasFile)
        {
            mail.Attachments.Add(new Attachment(fileUpload1.PostedFile.InputStream, fileUpload1.FileName));
        }
        if (fileUpload2.HasFile)
        {
            mail.Attachments.Add(new Attachment(fileUpload2.PostedFile.InputStream, fileUpload2.FileName));
        }
        if (fileUpload3.HasFile)
        {
            mail.Attachments.Add(new Attachment(fileUpload3.PostedFile.InputStream, fileUpload3.FileName));
        }
        if (fileUpload4.HasFile)
        {
            mail.Attachments.Add(new Attachment(fileUpload4.PostedFile.InputStream, fileUpload4.FileName));
        }
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
        smtp.Credentials = new System.Net.NetworkCredential("salikrammaurya@gmail.com", "password");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = true;
        smtp.Send(mail);
  
    }

}

Thursday 1 November 2012

Jquery For Calender

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.22/themes/base/jquery-ui.css" type="text/css" media="all" />
            <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
            <script src="http://code.jquery.com/ui/1.8.22/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function ($) {


        $(function () {
            $.datepicker.setDefaults($.datepicker.regional[""]);
            $(".datepicker").datepicker({ yearRange: "1901:2050"
, changeMonth: true,
                changeYear: true
            });


        });
        // Handler for .ready() called.
    });
  </script>
<style type="text/css">
    .datepicker
    {
        height:20px;
        width:150px;
    }
</style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <center>
    <table>
    <tr>
    <td>DOB:</td>
    <td><asp:TextBox ID="txtdob" runat="server" class="datepicker"></asp:TextBox></td>
    </tr>
    <tr>
    <td>DOJ:</td>
    <td><asp:TextBox ID="txtdoj" runat="server" class="datepicker"></asp:TextBox></td>
    </tr>
    <tr>
    <td colspan="2">
    <center>
    <asp:Button ID="btnsubmit" runat="server" Text="Submit" onclick="btnsubmit_Click" />
    </center>
    </td>
    </tr>
    </table>
    </center>
    </div>
    </form>
</body>
</html>

Dynamically Add and Remove Rows In GridView In Asp.Net


.aspx code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicGridview.aspx.cs" Inherits="DynamicGridview" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <center>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
            ShowFooter="true" onrowcommand="GridView1_RowCommand">
        <AlternatingRowStyle BackColor="#CCCCFF" BorderColor="#003366"
            BorderStyle="Solid" BorderWidth="1px" />
    <Columns>
    <asp:TemplateField HeaderText="Name">
    <ItemTemplate>
    <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Phone">
    <ItemTemplate>
    <asp:TextBox ID="txtphone" runat="server"></asp:TextBox>
    </ItemTemplate>
    <FooterTemplate>
    <center>
    <asp:Button ID="btnadd" runat="server" Text="Add New" CommandName="addnew" />
    </center>
    </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Email">
    <ItemTemplate>
    <asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Address">
    <ItemTemplate>
    <asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Delete">
    <ItemTemplate>
    <asp:Button ID="btndelete" runat="server" Text="Delete" CommandName="deleted" />
    </ItemTemplate>
    </asp:TemplateField>             
    </Columns>
        <EmptyDataRowStyle BackColor="White" />
        <FooterStyle BackColor="#336699" />
        <HeaderStyle BackColor="#336699" ForeColor="White" />
    </asp:GridView>
    </center>
    </div>
    </form>
</body>
</html>

.cs Code
--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class DynamicGridview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind_grid();
        }

    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       
        if (e.CommandName == "addnew")
        {
            addnewRow();
         
        }

        if (e.CommandName == "deleted")
        {
            Button btn = (Button)e.CommandSource;
            if (btn != null)
            {
                GridViewRow grdrow = (GridViewRow) btn.NamingContainer;
                int row = grdrow.RowIndex;
                deleteRow();
                DataTable dtt = (DataTable)ViewState["deleteRow"];

                if (dtt.Rows.Count > 1)
                {
                    dtt.Rows.RemoveAt(row);
                    dtt.AcceptChanges();
                }

                GridView1.DataSource = dtt;
                GridView1.DataBind();
               
            }

        }
    }
    public void bind_grid()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn ("Phone",typeof(string)));
        dt.Columns.Add(new DataColumn("Email", typeof(string)));
        dt.Columns.Add(new DataColumn("Address",typeof(string)));

        DataRow dr = dt.NewRow();
      
        dt.Rows.Add(dr);
        ViewState["CurrentTable"] = dt;
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    public void addnewRow()
    {
        DataTable dt1 = new DataTable();
        dt1.Columns.Add(new DataColumn("Name", typeof(string)));
        dt1.Columns.Add(new DataColumn("Phone", typeof(string)));
        dt1.Columns.Add(new DataColumn("Email", typeof(string)));
        dt1.Columns.Add(new DataColumn("Address", typeof(string)));

        for (int i = 0; i < GridView1.Rows.Count;i++ )
        {
            TextBox txt_name = (TextBox)GridView1.Rows[0].Cells[0].FindControl("txtname");
            TextBox txt_phone = (TextBox)GridView1.Rows[0].Cells[0].FindControl("txtphone");
            TextBox txt_email = (TextBox)GridView1.Rows[0].Cells[0].FindControl("txtemail");
            TextBox txt_address = (TextBox)GridView1.Rows[0].Cells[0].FindControl("txtaddress");

            DataRow dr = dt1.NewRow();
            dr["Name"] = txt_name.Text;
            dr["Phone"] = txt_phone.Text;
            dr["Email"] = txt_email.Text;
            dr["Address"] = txt_address.Text;
            dt1.Rows.Add(dr);
            dt1.AcceptChanges();
        }
        DataRow dr1 = dt1.NewRow();
        dr1["Name"] = string.Empty;
        dr1["Phone"] = string.Empty;
        dr1["Email"] = string.Empty;
        dr1["Address"] = string.Empty;

        dt1.Rows.Add(dr1);
        ViewState["deleteRow"] = dt1;
        GridView1.DataSource = dt1;
        GridView1.DataBind();
    }

    public void deleteRow()
    {
        DataTable dt1 = new DataTable();
        dt1.Columns.Add(new DataColumn("Name", typeof(string)));
        dt1.Columns.Add(new DataColumn("Phone", typeof(string)));
        dt1.Columns.Add(new DataColumn("Email", typeof(string)));
        dt1.Columns.Add(new DataColumn("Address", typeof(string)));

        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            TextBox txt_name = (TextBox)GridView1.Rows[0].Cells[0].FindControl("txtname");
            TextBox txt_phone = (TextBox)GridView1.Rows[0].Cells[0].FindControl("txtphone");
            TextBox txt_email = (TextBox)GridView1.Rows[0].Cells[0].FindControl("txtemail");
            TextBox txt_address = (TextBox)GridView1.Rows[0].Cells[0].FindControl("txtaddress");

            DataRow dr = dt1.NewRow();
            dr["Name"] = txt_name.Text;
            dr["Phone"] = txt_phone.Text;
            dr["Email"] = txt_email.Text;
            dr["Address"] = txt_address.Text;
            dt1.Rows.Add(dr);
            dt1.AcceptChanges();
        }
      
        ViewState["deleteRow"] = dt1;
        GridView1.DataSource = dt1;
        GridView1.DataBind();
    }
}

Monday 22 October 2012

 Download file in asp.net from gridview

 .aspx code
<asp:GridView ID="Grid_Circular_meeting" runat="server" AutoGenerateColumns="False"
                                CellPadding="4" Width="95%" EmptyDataText="No Record Exists!!!" AllowPaging="false"
                                ForeColor="#333333" GridLines="None" DataKeyNames="AutoId" OnRowCommand="Grid_Circular_meeting_RowCommand"
                                OnRowDeleting="Grid_Circular_meeting_RowDeleting" OnSelectedIndexChanged="Grid_Circular_meeting_SelectedIndexChanged">
                                <Columns>
                                    <asp:BoundField HeaderText="Title" DataField="Title" HeaderStyle-HorizontalAlign="Left">
                                        <HeaderStyle HorizontalAlign="Left" />
                                    </asp:BoundField>
                                    <asp:BoundField HeaderText="MeetingDate" DataField="MeetingDate" DataFormatString="{0:dd-MMM-yyyy}"
                                        HeaderStyle-HorizontalAlign="Left">
                                        <HeaderStyle HorizontalAlign="Left" />
                                    </asp:BoundField>
                                    <asp:BoundField HeaderText="Location" DataField="Location" DataFormatString="{0:dd-MMM-yyyy}"
                                        HeaderStyle-HorizontalAlign="Left">
                                        <HeaderStyle HorizontalAlign="Left" />
                                    </asp:BoundField>
                                    <asp:BoundField HeaderText="MeetingTime" DataField="MeetingTime" HeaderStyle-HorizontalAlign="Left">
                                        <HeaderStyle HorizontalAlign="Left" />
                                    </asp:BoundField>
                                    <asp:BoundField HeaderText="File" DataField="FileCName" NullDisplayText="no file" />
                                    <asp:BoundField HeaderText="FilePath" DataField="FilePath" Visible="false" />
                                    <asp:TemplateField HeaderText="Show" HeaderStyle-HorizontalAlign="Left" Visible="true">
                                        <ItemTemplate>
                                            <asp:ImageButton ID="bthshow" runat="server" ImageUrl="~/Images/btnshow.jpg" CommandArgument='<%#Eval("FilePath") %>'
                                                CommandName="download" ToolTip="show" Width="35px" Height="25px" />
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Left" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Delete" HeaderStyle-HorizontalAlign="Left">
                                        <ItemTemplate>
                                            <asp:ImageButton ID="btndelete" runat="server" ImageUrl="~/Images/close-button.gif"
                                                CommandArgument='<%#Eval("AutoId") %>' CommandName="deleted" ToolTip="show" Width="35px" Height="25px" />
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Left" />
                                    </asp:TemplateField>
                                </Columns>
                                <AlternatingRowStyle BackColor="White" HorizontalAlign="Left" />
                                <EditRowStyle BackColor="#2461BF" />
                                <FooterStyle BackColor="#507CD1" ForeColor="White" Font-Bold="True" />
                                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
                                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                                <RowStyle BackColor="#EFF3FB" HorizontalAlign="Left" />
                                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                                <SortedAscendingCellStyle BackColor="#F5F7FB" />
                                <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                                <SortedDescendingCellStyle BackColor="#E9EBEF" />
                                <SortedDescendingHeaderStyle BackColor="#4870BE" />
                            </asp:GridView>

.CS Code

if (e.CommandName == "download")
            {
                string filename = e.CommandArgument.ToString();
                if (filename != "")
                {
                    string path = MapPath(filename);
                    byte[] bts = System.IO.File.ReadAllBytes(path);
                    Response.Clear();
                    Response.ClearHeaders();
                    Response.AddHeader("Content-Type", "Application/octet-stream");
                    Response.AddHeader("Content-Length", bts.Length.ToString());

                    Response.AddHeader("Content-Disposition", "attachment;   filename=" + filename);

                    Response.BinaryWrite(bts);

                    Response.Flush();

                    Response.End();
                }
            }

Friday 19 October 2012

 Dynamically Add and Delete row in GridView 

.aspx code
-----------
<div>
 <asp:GridView ID="gvBooks" runat="server" ShowFooter="True"
                                AutoGenerateColumns="False" HeaderStyle-CssClass="header-column" onrowcommand="gvBooks_RowCommand"
                                onrowdatabound="gvBooks_RowDataBound" BorderStyle="None" GridLines="None">
                                <Columns>
                                    <asp:TemplateField HeaderText="Book Name">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtBookName" runat="server">
                                            </asp:TextBox>
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            <asp:LinkButton ID="lbNewBook" runat="server" CausesValidation="false" CommandName="NewBook">New</asp:LinkButton>
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Author">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtAuthor" runat="server" Text='<%#Bind("Author") %>'></asp:TextBox>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Description">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtDescription" runat="server" Text='<%#Bind("Description") %>'></asp:TextBox>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Genre">
                                        <ItemTemplate>
                                            <asp:DropDownList ID="ddlGenre" runat="server" AppendDataBoundItems="true">
                                            <asp:ListItem>Choose...</asp:ListItem>
                                            <asp:ListItem>Computer</asp:ListItem>
                                            <asp:ListItem>Fantasy</asp:ListItem>
                                           <asp:ListItem>Horror</asp:ListItem>
                                           <asp:ListItem>Comedy</asp:ListItem>
                                            </asp:DropDownList>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Price">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtPercentage" runat="server" Width="100px" Text='<%#Bind("Price") %>'></asp:TextBox>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Publish Date">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtPublishDate" runat="server" Width="100px" Text='<%#Bind("PublishDate") %>'></asp:TextBox>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:ImageButton ID="imgbtnDeleteBook" runat="server" CausesValidation="false" ImageUrl="~/App_Themes/Red/Images/cross.png" CommandName="DeleteBook" />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>
                        </div>
.cs code

public partial class Default6 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            AddBookDefault();
        }
    }

    private void AddBookDefault()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("BookName", typeof(string)));
        dt.Columns.Add(new DataColumn("Author", typeof(string)));
        dt.Columns.Add(new DataColumn("Description", typeof(string)));
        dt.Columns.Add(new DataColumn("Genre", typeof(string)));
        dt.Columns.Add(new DataColumn("Price", typeof(string)));
        dt.Columns.Add(new DataColumn("PublishDate", typeof(string)));

        dr = dt.NewRow();

        dr["BookName"] = string.Empty;
        dr["Author"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Genre"] = string.Empty;
        dr["Price"] = string.Empty;
        dr["PublishDate"] = string.Empty;

        dt.Rows.Add(dr);
        //dr = dt.NewRow();
        //Store the DataTable in ViewState

        ViewState["CurrentTable"] = dt;

        gvBooks.DataSource = dt;
        gvBooks.DataBind();
    }
    protected void gvBooks_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int rowIndex = 0;
        DataTable dt = (DataTable)ViewState["CurrentTable"];

        if (e.CommandName == "NewBook")
        {
            DataRow rw = dt.NewRow();
            dt.Rows.Add(rw);

            //Set Previous Data
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count - 1; i++)
                {
                    TextBox txtBookName = (TextBox)gvBooks.Rows[rowIndex].Cells[0].FindControl("txtBookName");
                    TextBox txtAuthor = (TextBox)gvBooks.Rows[rowIndex].Cells[1].FindControl("txtAuthor");
                    TextBox txtDescription = (TextBox)gvBooks.Rows[rowIndex].Cells[2].FindControl("txtDescription");
                    DropDownList ddlGenre = (DropDownList)gvBooks.Rows[rowIndex].Cells[3].FindControl("ddlGenre");
                    TextBox txtPrice = (TextBox)gvBooks.Rows[rowIndex].Cells[4].FindControl("txtPercentage");
                    TextBox txtPublishDate = (TextBox)gvBooks.Rows[rowIndex].Cells[5].FindControl("txtPublishDate");

                    dt.Rows[i]["BookName"] = txtBookName.Text;
                    dt.Rows[i]["Author"] = txtAuthor.Text;
                    dt.Rows[i]["Description"] = txtDescription.Text;
                    dt.Rows[i]["Genre"] = ddlGenre.SelectedItem.Text;
                    dt.Rows[i]["Price"] = txtPrice.Text;
                    dt.Rows[i]["PublishDate"] = txtPublishDate.Text;

                    rowIndex++;
                }
            }
        }
        else if (e.CommandName == "DeleteBook")
        {
            GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
            dt.Rows.RemoveAt(gvr.RowIndex);
        }

        gvBooks.DataSource = dt;
        gvBooks.DataBind();
    }

    protected void gvBooks_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlGenre = (DropDownList)e.Row.Cells[3].FindControl("ddlGenre");

            ddlGenre.SelectedValue = DataBinder.Eval(e.Row.DataItem, "Genre").ToString();
        }
    }

}