Sunday, 30 August 2015

Export Gridview Data with Images to Word, Excel in Asp.net using C#


// HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
<title>Export Gridview with Images in Asp.net</title>
<style type="text/css">
.GridviewDiv {font-size100%font-family'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial,Helevetica, sans-serifcolor#303933;}
.headerstyle
{
color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;background-color:#df5015;padding:0.5em 0.5em 0.5em 0.5em;text-align:center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="GridviewDiv">
<asp:GridView ID="gvDetails" CssClass="Gridview" runat="server" AutoGenerateColumns="False">
<HeaderStyle CssClass="headerstyle" />
<Columns>
<asp:BoundField HeaderText="User Id" DataField="UserId" />
<asp:BoundField HeaderText="User Name" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:ImageField DataImageUrlField="Imagepath" HeaderText="Image" ItemStyle-Height="25px"ItemStyle-Width="25px" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExport" runat="server" Text="Export Data"
onclick="btnExport_Click" />
</div>
</form>
</body>
</html>

// CS Page

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvDetails.DataSource = BindGridviewData();
gvDetails.DataBind();
}
}
public override void VerifyRenderingInServerForm(Control control)
{

}
/// <summary>
/// Dynamically create & bind data to gridview
/// </summary>
protected DataTable BindGridviewData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId"typeof(Int32));
dt.Columns.Add("UserName"typeof(string));
dt.Columns.Add("Education"typeof(string));
dt.Columns.Add("Imagepath"typeof(string));
dt.Rows.Add(1, "Raja""MCA""http://localhost:50157/Blog Samples/uploads/Sign1.jpg");
dt.Rows.Add(2, "Krishna""Msc""http://localhost:50157/Blog Samples/uploads/Signature.jpg");
dt.Rows.Add(3, "Mohit""MS","");
dt.Rows.Add(4, "Arun""B.Tech","");
dt.Rows.Add(6, "Ajay""MD","");
dt.Rows.Add(7, "Rohit""B.Tech","http://localhost:50157/Blog Samples/uploads/Rohit.jpg");
dt.Rows.Add(8, "Anuraj""CA","");
return dt;
}
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition"string.Format("attachment; filename={0}","EmpDetails.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvDetails.AllowPaging = false;
gvDetails.DataSource = BindGridviewData();
gvDetails.DataBind();
//Change the Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color""#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvDetails.HeaderRow.Cells.Count; i++)
{
gvDetails.HeaderRow.Cells[i].Style.Add("background-color""#df5015");
}
gvDetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Generate One Time Password (OTP) in Asp.net using C#

// HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>OPT Password in Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Number of OPT Digit: <asp:TextBox ID="txtCharacters" runat="server"/>
<asp:Button ID="btnGenerate" Text="Generate" runat="server"
onclick="btnGenerate_Click" /><br />
<asp:Label ID="lblResult" runat="server" ForeColor="Red" />
</div>
</form>
</body>
</html>


//CS Page

protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnGenerate_Click(object sender, EventArgs e)
{
// declare array string to generate random string with combination of small,capital letters and numbers
char[] charArr ="0123456789abcdefghijklmnopqrstuvwxyz@#$<>ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
string strrandom = string.Empty;
Random ran = new Random();
int noofcharacters = Convert.ToInt32(txtCharacters.Text);
for (int i = 0; i < noofcharacters; i++)
{
//It will not allow Repetation of Characters
int pos = ran .Next(1, charArr.Length);
if (!strrandom.Contains(charArr.GetValue(pos).ToString()))
strrandom += charArr.GetValue(pos);
else
i--;
}
lblResult.Text = strrandom;
}

Monday, 24 August 2015

Export Datatable into PDF using asp.net c#


private void GeneratePDF(DataTable dataTable, string rptnm)
    {
        Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
        System.IO.MemoryStream mStream = new System.IO.MemoryStream();
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
        int cols = dataTable.Columns.Count;
        int rows = dataTable.Rows.Count;
        pdfDoc.Header = new HeaderFooter(new Phrase("Header Text”,false);
        pdfDoc.Open();
        iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
        pdfTable.BorderWidth = 1;pdfTable.Width = 100;
        pdfTable.Padding = 1;pdfTable.Spacing = 1;

        //creating table headers
        for (int i = 0; i < cols; i++)
        {
            Cell cellCols = new Cell();
            cellCols.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#548B54"));
            iTextSharp.text.Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.WHITE);
            Chunk chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);
            cellCols.Add(chunkCols);
            pdfTable.AddCell(cellCols);
        }
        //creating table data (actual result)

        for (int k = 0; k < rows; k++)
        {
            for (int j = 0; j < cols; j++)
            {
                Cell cellRows = new Cell();
                if (k % 2 == 0)
                {
                    cellRows.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#cccccc")); ;
                }
                else { cellRows.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#ffffff")); }
                iTextSharp.text.Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
                Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
                cellRows.Add(chunkRows);

                pdfTable.AddCell(cellRows);
            }
        }
        pdfDoc.Add(pdfTable);
        pdfDoc.Close();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
        Response.Clear();
        Response.BinaryWrite(mStream.ToArray());
        Response.End();

    }

Export gridview into PDF using asp.net c#


private void ExportGridToword()
    {
        DataTable dt = ViewState["dtt"] as DataTable;
        GridView gv = new GridView();
        gv.HeaderStyle.BackColor = System.Drawing.Color.Red;// System.Drawing.ColorTranslator.FromHtml("#DDDDDD");
        gv.HeaderStyle.ForeColor = System.Drawing.Color.LightGray;// System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
        gv.RowStyle.BackColor = System.Drawing.Color.LightCyan;// System.Drawing.ColorTranslator.FromHtml("#454545");
        gv.AlternatingRowStyle.BackColor = System.Drawing.Color.White;// System.Drawing.ColorTranslator.FromHtml("#545454");
        gv.DataSource = dt;
        gv.DataBind();

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=krishraja.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);      

        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        gv.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);       
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Header = new HeaderFooter(new Phrase("Header Text"), false);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }


Wednesday, 19 August 2015

Add leading zeros in access

There are tow types of leading zeros-

1. Test type fields with numeric values-
     
            select Format(fieldname, '000000000000')as [WithZeros],  * from TableName


2. Test type fields with text values

      select  String(9-Len([fieldname]),"0")&[WithZeros] as [ttt],  * from TableName

Wednesday, 22 July 2015

Dynamic Menu in asp.net using Sql database

//Data Base







//  HTML ------------------------------------------------------------------

  <asp:repeater ID="rptCategories" runat="server" OnItemDataBound="rptCategories_ItemDataBound">
                    <headertemplate>
                        <div class="menu"><ul>
                    </ul></div></headertemplate>
                    <itemtemplate>
                        <li>
                            <a href='#'>< %#Eval("Name") %></a>
                            <asp:literal ID="ltrlSubMenu" runat="server"></asp:literal>
                        </li>
                    </itemtemplate>
                <footertemplate>
                   
                </footertemplate>
                </asp:repeater>








//.CS Page


    DataTable allCategories = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadCategories();
        }
    }
    private void LoadCategories()
    {
        allCategories = GetAllCategories();
        rptCategories.DataSource = GetCategories();
        rptCategories.DataBind();
    }
    private void GetCategories()
        {
        SqlConnection connection = new SqlConnection("Data Source=NITESH;Initial Catalog=TestDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient");
        SqlCommand selectCommand = new SqlCommand("SELECT ID,CategoryName FROM Categories WHERE ParentCategoryID=0", connection);
        DataTable dt = new DataTable();
        try
        {
            connection.Open();
            SqlDataReader reader = selectCommand.ExecuteReader();
            if (reader.HasRows)
            {
                dt.Load(reader);
            }
            reader.Close();
        }
        catch (SqlException)
        {
            throw;
        }
        finally
        {
            connection.Close();
        }
        }
    private void GetAllCategories()
        {
        SqlConnection connection = new SqlConnection("Data Source=NITESH;Initial Catalog=TestDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient");
        SqlCommand selectCommand = new SqlCommand("SELECT ID,CategoryName FROM Categories", connection);
        DataTable dt = new DataTable();
        try
        {
            connection.Open();
            SqlDataReader reader = selectCommand.ExecuteReader();
            if (reader.HasRows)
            {
                dt.Load(reader);
            }
            reader.Close();
        }
        catch (SqlException)
        {
            throw;
        }
        finally
        {
            connection.Close();
        }
        }
    protected void Categories_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            if (allCategories != null)
            {
                DataRowView drv = e.Item.DataItem as DataRowView;
                string ID = drv["ID"].ToString();
                DataRow[] rows = allCategories.Select("ParentCategoryID=" + ID, "Name");
                if (rows.Length > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<ul>");
                    foreach (var item in rows)
                    {
                        sb.Append("<li><a href='#'>" + item["CategoryName"] + "</a></li>");
                    }
                    sb.Append("</ul>");
                    (e.Item.FindControl("ltrlSubMenu") as Literal).Text = sb.ToString();
                }
            }
        }
    }



//CSS --------------------------------------------------------------------------


.menu{
    width: 500px;
    margin: 0px auto;
    font-family: Arial, Helvetica, sans-serif;
    font-weight: bold;
    font-size: 14px;
}
.menu ul li a:link, div ul li a:visited {
    display: block;
    background-color: #f1f1f1;color:#000;
    text-align: center;
    text-decoration: none;
    padding: 4px;
    border-bottom: 1px solid #fff;
    width: 150px;      
}
.menu ul li a:hover{
    background-color: #ccc;
}
.menu ul li ul li a:link, li ul li a:visited {
    display: block;
    background-color: #f1f1f1;
    color: #000;
    text-align: center;
    text-decoration: none;
    padding: 4px;
    border-bottom: 1px solid #fff;
    width: 150px;
}
.menu ul li ul li a:hover {
    background-color: #ccc;
}
.menu ul {
    list-style-type: none;
    margin: 0px;
    padding: 0px;  
}
.menu ul li {
    float: left;
    margin-left: 5px;
}
.menu ul li ul li {
    float: none;
    margin-left: 0px;
}
.menu ul li ul {
    display: none;
}
.menu li:hover ul{
    display: block;
}


// Result



How to highlight selected text in notepad++

  –> To highlight a block of code in Notepad++, please do the following steps step-1  :- Select the required text. step-2  :- Right click...