Monday 2 December 2013

Import Data from Excel Sheet into Asp.Net Gridview using EPPlus.

Introduction:
Here I will explain how to import data from excel to gridview in asp.net using EPPlus in C#.
Description:
  • ·         Create a new C# console application project in Visual Studio. Download the EPPlus binaries from the Downloads section on the EPPlus CodePlex Site 
  • ·         Extract the files and add EPPlus.dll as a reference to your project.


Step 1:
Write the blow code to Default.aspx page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:FileUpload ID="FileUploadToServer" Width="300px" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload File"
            ValidationGroup="vg" style="width: 99px" onclick="btnUpload_Click" />
        <br />
        <br />
        <asp:Label ID="lblMsg" runat="server" ForeColor="Green" Text=""></asp:Label>
        <br />
     <asp:GridView ID="gvRecord" runat="server" EmptyDataText="No record found!"
            Height="25px">
            <RowStyle Width="175px" />
            <EmptyDataRowStyle BackColor="Silver" BorderColor="#999999" BorderStyle="Solid"
                BorderWidth="1px" ForeColor="#003300" />
            <HeaderStyle BackColor="#6699FF" BorderColor="#333333" BorderStyle="Solid"
                BorderWidth="1px" VerticalAlign="Top" Width="200px"  Wrap="True" />
             
        </asp:GridView>
    </div>
    </form>
</body>
</html>
Step 2:
Write the blow code to Default.aspx.cs page.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
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 OfficeOpenXml;
using System.IO;

public partial class Epplus_New : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        ImportToDataTable();
    }
    public void ImportToDataTable()
    {
        DataTable dt = new DataTable();
        string filePath = Server.MapPath("Product1.xlsx");
        var existingFile = new FileInfo(filePath);
        using (var package = new ExcelPackage(existingFile))
        {
            ExcelWorkbook workBook = package.Workbook;
            if (workBook != null)
            {
                if (workBook.Worksheets.Count > 0)
                {
                    ExcelWorksheet worksheet = workBook.Worksheets.First();
                    ExcelCellAddress startCell = worksheet.Dimension.Start;
                    ExcelCellAddress endCell = worksheet.Dimension.End;


                    for (int col = startCell.Column; col <= endCell.Column; col++)
                    {
                        object col1Header1 = worksheet.Cells[1, col].Value;
                        dt.Columns.Add("" + col1Header1 + "");
                    }
                    for (int row = startCell.Row + 1; row <= endCell.Row + 1; row++)
                    {
                        DataRow dr = dt.NewRow();
                        int x = 0;
                        for (int col = startCell.Column; col <= endCell.Column; col++)
                        {
                            dr[x++] = worksheet.Cells[row, col].Value;
                        }
                        dt.Rows.Add(dr);
                        gvRecord.DataSource = dt;
                        gvRecord.DataBind();
                    }
                }

            }

        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
        string filename = string.Empty;
        if (FileUploadToServer.HasFile)
        {

            string[] allowdFile = { ".xls", ".xlsx" };
            string FileExt = System.IO.Path.GetExtension(FileUploadToServer.PostedFile.FileName);
            bool isValidFile = allowdFile.Contains(FileExt);
            if (!isValidFile)
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = "Please upload only Excel";
            }
            else
            {
                int FileSize = FileUploadToServer.PostedFile.ContentLength;
                if (FileSize <= 1048576)
                {
                    filename = Path.GetFileName(Server.MapPath(FileUploadToServer.FileName));
                    FileUploadToServer.SaveAs(Server.MapPath(FilePath) + filename);
                    string filePath = Server.MapPath(FilePath) + filename;

                }
            }
        }

    }
}




Untitled Page

























Sunday 24 November 2013

How to Create ContactUs page using Rich TextBox in Asp.Net

Introduction:

As we know, ASP.NET lacks a control that we need most, RichText editor.

If you are trying to create an application or website with Admin Panel or Blog or Forum Website or some such project for Web in ASP.NET platform, we need RichText Editor.
To overcome this, we can use many open source JavaScript based editors, like Tiny MCE, FCKEditor, etc.

here we are using TinyMCE, which is one of the most popular and Open Source projects. Download the latest version of TinyMCE from download page, and extract the zip file.

Steps:

Create a new WebPage  in VS 2008.

Browse the extracted location and go to ..\tinymce_3.5.6\tinymce\jscripts folder.
Now copy the tinymce folder from the above location to your solution in Visual Studio.

Step 1:

Create a WebPage file named ContactUs.aspx.

Paste the code below into ContactUs.aspx:



<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Contact Us Form</title>
    <script type="text/javascript" src="tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
   tinyMCE.init({
        mode : "textareas",
        theme : "advanced",
        plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager",
        theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : false,
        template_external_list_url : "js/template_list.js",
        external_link_list_url : "js/link_list.js",
        external_image_list_url : "js/image_list.js",
        media_external_list_url : "js/media_list.js"
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<table border = "0" style="width: 409px">
    <tr>
        <td>
            <asp:Label ID="Label1" runat="server" Text="Name*"></asp:Label><br />
        </td>
        <td>
            <asp:TextBox ID="txtName" runat="server" ValidationGroup = "contact"></asp:TextBox><br />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
             ControlToValidate = "txtName"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="Label2" runat="server" Text="Subject*"></asp:Label><br />
        </td>
        <td>
            <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox><br />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*"
             ControlToValidate = "txtSubject"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="Label3" runat="server" Text="Email*"></asp:Label><br />
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
            <asp:RegularExpressionValidator id="valRegEx" runat="server"
            ControlToValidate="txtEmail"
            ValidationExpression=".*@.*\..*"
            ErrorMessage="*Invalid Email address."
            display="dynamic">
            </asp:RegularExpressionValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*"
            ControlToValidate = "txtEmail"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td valign = "top" >
            <asp:Label ID="Label4" runat="server" Text="Body*"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtBody" runat="server" TextMode = "MultiLine" ></asp:TextBox><br />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*"
            ControlToValidate = "txtBody"></asp:RequiredFieldValidator>
        </td>
    </tr>
     <tr>
        <td></td>
        <td>
            <asp:FileUpload ID="FileUpload1" runat="server" />
       </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
       </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <asp:Label ID="lblMessage" runat="server" Text="" ForeColor = "Green"></asp:Label>
       </td>
    </tr>
</table>
</div>
    </form>
</body>
</html>


Paste this code into ContactUs.aspx.cs:

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

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

    }
protected void btnSend_Click(object sender, EventArgs e)
{
    MailMessage mm = new MailMessage("sender@gmail.com", "receiver@gmail.com");
    mm.Subject = txtSubject.Text;
    mm.Body = "Name: " + txtName.Text + "<br /><br />Email: " + txtEmail.Text + "<br />" + txtBody.Text;
    if (FileUpload1.HasFile)
    {
        string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName)   ;
        mm.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileName));
    }
    mm.IsBodyHtml = true;
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.EnableSsl = true;
    System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
    NetworkCred.UserName = "sender@gmail.com";
    NetworkCred.Password = "xxxxx";
    smtp.UseDefaultCredentials = true;
    smtp.Credentials = NetworkCred;
    smtp.Port = 587;
    smtp.Send(mm);
    lblMessage.Text = "Email Sent SucessFully.";
}
}