Pages

Subscribe:

Ads 468x60px

Monday, October 15, 2012

How to Go back from current webpage in asp.net suing c#

In this web Programming tutorial we will learn that how we can go back from Current web page to previous one by clicking on the HTML button.
 

How to print a web page using javascript.

In this web Programming tutorial we will learn that how we can add Printing functionality on our web page using javascript in a asp.net or simple html page. see the below code and just copy and paste it.
 
Code to use in HTML part you want to print.
  
// Content Will goes here you want to print.

how to reboot or Restart your computer from web page in asp.net using c#

In this web-healer.blogspot.com's web programming tutorial we will learn that how we can Restart our computer by clicking on a button from our website. So below is the dream code just copy and paste it. and use it in your button's onClick event.
 System.Diagnostics.Process.Start("shutdown.exe", "-r -t 0");

how to shutdown you computer from website in asp.net using c#

In this web-healer.blogspot.com's web programming tutorial we will learn that how we can shutdown our computer by clicking on a button from our website. So below is the dream code just copy and paste it. and use it in your button's onClick event.
System.Diagnostics.Process.Start("shutdown.exe", "-s -t 0")

how to sow date and time on a asp.net page using c#

In this web-healer.blogspot.com's web programming tutorial we will learn that how we can show simple date and time on our web page in asp.net using c#. just copy and paste the below code.
 if (!Page.IsPostBack)
        {
            lbl_date.Text = DateTime.Now.ToLongDateString();
            TxtDateTo.Text = DateTime.Today.ToString("MM/dd/yyyy");
        }  

how to call a javascript function from server side page load event in asp.net using c#

In this web programming tutorial we will learn that how we can call a javascript function from server side in asp.net using c#. see the below simple code in which we are trying to call a radiobutton click event that is defined in Client side, but we will call it on page load event in asp.net using c#. Javascript Function in head section
 
Code for Function call in .CS file on Server side in page load event.
   protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {    
         RBAllHis.Attributes.Add("onclick", "others()");
        }
    }       
 

Saturday, October 13, 2012

import to excel in asp.net using c#

In this web programming tutorial we will learn that how we can import our Gridview data into excel file by click on a link button from our webpage in asp.net using c#.
  protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");        
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);     
        this.ClearControls(GridView1);
        GridView1.RenderControl(htw);       
        Response.Write(sw.ToString());
        Response.End();
    }
  private void ClearControls(Control ctrl)
    {
        for (int i = ctrl.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(ctrl.Controls[i]);
        }

        if (!(ctrl is TableCell))
        {
            if (ctrl.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                ctrl.Parent.Controls.Add(literal);
                try
                {
                    literal.Text = (string)ctrl.GetType().GetProperty("SelectedItem").GetValue(ctrl, null);
                }
                catch
                {

                }

                ctrl.Parent.Controls.Remove(ctrl);
            }

            else

                if (ctrl.GetType().GetProperty("Text") != null)
                {
                    if (ctrl.Visible == true)
                    {
                        LiteralControl literal = new LiteralControl();
                        ctrl.Parent.Controls.Add(literal);
                        literal.Text = (string)ctrl.GetType().GetProperty("Text").GetValue(ctrl, null);
                        ctrl.Parent.Controls.Remove(ctrl);
                    }
                }
        }
        return;

    }

how to clear all gridview elements in aps.net using c#

In this simple web Programming tutorial we will learn that how we can clear all Controls available in a gridview by just one click instead clearing one by one. like as we clear a form's text fields or other form elements. just copy the below code in your .CS file. Function call.
        this.ClearControls(GridView1);
        GridView1.RenderControl(htw);
Method to clear Gridview fields.
 private void ClearControls(Control ctrl)
    {
        for (int i = ctrl.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(ctrl.Controls[i]);
        }

        if (!(ctrl is TableCell))
        {
            if (ctrl.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                ctrl.Parent.Controls.Add(literal);
                try
                {
                    literal.Text = (string)ctrl.GetType().GetProperty("SelectedItem").GetValue(ctrl, null);
                }
                catch
                {
                }
                ctrl.Parent.Controls.Remove(ctrl);
            }
            else
                if (ctrl.GetType().GetProperty("Text") != null)
                {
                    if (ctrl.Visible == true)
                    {
                        LiteralControl literal = new LiteralControl();
                        ctrl.Parent.Controls.Add(literal);
                        literal.Text = (string)ctrl.GetType().GetProperty("Text").GetValue(ctrl, null);
                        ctrl.Parent.Controls.Remove(ctrl);
                    }
                }
            }
        return;
    }


how to define session as string in asp.net using c#

In this simple web programming tutorial we will learn that how we can define a Session as string in asp.net using C# to assign it to a string veriable. see the written below code and just copy and paste it.

  string data = Session["Data_var"] as string;

How to find the Previous Page Control's value on a current page in asp.net using c#

In this web Programming tutorial we will learn that how we can find or access a control like label, Dropdown, radiobutton, textbox etc from a previous page and its value to use in current page from gridview in asp.net using c#.
See the below code and just copy and paste the code and have fun.
  
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
     if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (!empty)
            {                
                Label lblcharges = e.Row.FindControl("lbl_charges") as Label;  
             }
         }  
   }

Control Function method .CS file of Current page to access the control's Value.

   private Control FindControl(string controlID, ControlCollection controls)
    {
        foreach (Control c in controls)
        {

            if (c.ID == controlID)

                return c;
            if (c.HasControls())
            {
                Control cTmp = this.FindControl(controlID, c.Controls);

                if (cTmp != null)

                    return cTmp;
            }

        }
        return null;
    }

  

Format String into Money Format in asp.net using c#

In this programming Tutorial we will learn that how we can format amount string into money. below is the code just copy and paste and use it.

string charges = "125.35";
lbl_charges_total.Text  = string.Format("{0:###,###,##0.00}", charges);

Friday, October 12, 2012

how to add new row in gridview in asp.net using c#

In this web programming tutorial we will learn how we can add new column in a Gridview when there is no record and we want to show a proper message that there is no data against particular search in asp.net using c#. see the below code and copy and past.
          
              int columncount = GridView1.Rows[0].Cells.Count;
              GridView1.Rows[0].Cells.Clear();
              GridView1.Rows[0].Cells.Add(new TableCell());
              GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
              GridView1.Rows[0].Cells[0].Text = "No Record Found ";
              GridView1.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
              GridView1.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Maroon;
          

Friday, October 5, 2012

Free Download µTorrent 3.2.1 Full Version

Download


Features that make Torrent so popular.
Tiny

Tiny

µTorrent is less than 800 KB (smaller than a digital photo!). It installs ultra-fast with a light footprint on your computer, and runs super-efficiently.
Easy

Easy

Simple and straightforward – that's µTorrent. With its purpose-built interface, downloading torrents is a snap.
Accessible

Accessible

Access µTorrent from anywhere with µTorrent Remote. Easily access your home clients securely (using ultra-private authentication and key-exchange).
Innovative

Innovative

Since µTorrent is offered by the team who invented the BitTorrent open source protocol, you know you will always have access to the latest and greatest technologies.
Fast

Fast

Expertly designed for fast downloads. Avoids hogging valuable system resources, runs quietly in the background, and doesn't interfere with your work, play etc.
Cuttingedge

Cutting Edge

Incorporating groundbreaking µTP technology, µTorrent maximizes bandwidth and reduces congestion - so you have the smoothest, quickest downloads possible and don't make your internet connection slow to a crawl.
Intelligent

Intelligent

µTorrent is instinctively smart. It auto-adjusts bandwidth usage based upon your network and the Internet. Use Skype, play games, stream video etc., all without interference.
Plug n Play

Plug-n-Play

µTorrent is a snap to install on your home network. In most cases, it's plug-n-play. We also use UPnP and NAT-PMP technologies to prepare your router for torrent access.
Download

Wednesday, October 3, 2012

Free Download Internet Download Manager v6.05 build 11 Full Version

Internet Download Manager v6.05 build 11. Fixed compatibility problems with different browsers including IE 9.0  Final, Mozilla Firefox 4, Google Chrome. Improved FLV grabber to save videos from  Online Video players Such as  on YouTube, WOW! Google Video, MySpace TV and other popular Live Video Streaming sites..


Internet Download Manager V6.05 Build 11. (IDM) is a such tool which increases download speeds by up to 8 times, resume and schedule downloads. Comprehensive error recovery and resume capability will restart broken or interrupted downloads due to lost connections, network problems, computer shutdowns, or unexpected power outages. Simple graphic user interface makes IDM user friendly and easy to use.Internet Download Manager has a smart download logic accelerator that features intelligent dynamic file segmentation and safe multipart downloading technology to accelerate your downloads. Unlike other download managers and accelerators Internet Download Manager segments downloaded files dynamically during download process and reuses available connections without additional connect and login stages to achieve best acceleration performance. Internet Download Manager supports proxy servers, ftp and http protocols, firewalls, redirects, cookies, authorization, MP3 audio and MPEG video content processing. IDM integrates seamlessly into Microsoft Internet Explorer, Netscape, MSN Explorer, AOL, Opera, Mozilla, Mozilla Firefox, Mozilla Firebird, Avant Browser, MyIE2, and all other popular browsers to automatically handle your downloads. You can also drag and drop files, or use Internet Download Manager from command line. Internet Download Manager can dial your modem at the set time, download the files you want, then hang up or even shut down your computer when it's done. Other features include multilingual support, zip preview, download categories, scheduler pro, sounds on different events, HTTPS support, queue processor, html help and tutorial, enhanced virus protection on download completion, progressive downloading with quotas (useful for connections that use some kind of fair access policy or FAP like Direcway, Direct PC, Hughes, etc.), built-in download accelerator, and many others. Version 6.05 adds IDM download panel for web-players that can be used to download flash videos from sites like YouTube, MySpaceTV, and Google Videos. It also features complete Windows 7and Vista support, YouTube grabber, redeveloped scheduler, and MMS protocol support. The new version also adds improved integration for IE and IE based browsers, redesigned and enhanced download engine, the unique advanced integration into all latest browsers, improved toolbar, and a wealth of other improvements and new features.

Download From he following Link Directly.

Click On the Image to downlaod


Click Here to download

Monday, October 1, 2012

Download Free Adobe Photoshop 7.0 For Free

Adobe photoshop is the best software for Graphics designing and photo editing either for photography or web designing or Template designing or Making logos or any other thing related to photography. photo shop provide best and easy way to do all this. below is the link to download free registered adobe photo shop shoftware to download. just download it and install it. and have fun. In order to download Adobe Photoshop  click on below picture link.

Click here to download Photoshop

Saturday, September 1, 2012

How to format string money or currency format in asp.net using c#

In this web programming tutorial we will learn that how we can convert a string into money format in asp.net using c#. see the below code
Total_amount.Text = string.Format("{0:###,###,##0.00}", Total_Amountdue);

Thursday, August 30, 2012

how to upload file or image on FTP using asp.net uploader in asp.net using c#

In this web programming tutorial we will learn that how we can upload an image or file directly on FTP by using asp.net file uploader control in asp.net using c# see the below code it will help us by doing so.. just copy and paste.
public void ftpfile(string ftpfilepath)
 {
     string ftphost = "Domain";
     //here correct hostname or IP of the ftp server to be given  
 
     string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
     FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
     ftp.Credentials = new NetworkCredential("Domain", "Password");
     //userid and password for the ftp server to given  
 
     ftp.KeepAlive = true;
     ftp.UseBinary = true;
     ftp.Method = WebRequestMethods.Ftp.UploadFile;
      
     // Resize Image is function to resize the image 
     System.Drawing.Image img1 = 
         ResizeImage(FileUpload1.PostedFile.InputStream, 84, 118);
 
     // Convert the image into bytes Array;
     byte[] buffer = ImageToByte(img1);
  
     // Send the image file in form of bytes
     Stream ftpstream = ftp.GetRequestStream();
     ftpstream.Write(buffer, 0, buffer.Length);
     ftpstream.Close();
}

how to concatenate Strings in asp.net using C#

In this web programming tutorial we will learn that how we can concatenate strings in asp.net using c#. just copy and paste the below code.
 string practice = "Adress1" + "," Karachi ", "state" + "4600";

Saturday, June 2, 2012

how to show prompt box using javascript

In this web programming tutorial we will learn that how we can use Javascript Prompt function on our web pages. see the below code and just copy and paste it as it is.

 
    Javascript Prompt Box
 

 
      




Thursday, May 31, 2012

how to upload photo or picture in asp.net using c#

In this web programming tutorial we will learn that how we can upload a picture or photo in asp.net using c#. just copy and paste below code in you .cs file.
protected void btn_upload_Click(object sender, EventArgs e)
    {
        imageflag = 1;
 
        if (!FileUpload_image.HasFile)
        {
            Alert.Show("No file for uploading");
            return;
        }
        if (FileUpload_image.HasFile)
        {
            //string imagetype = FileUpload_image.PostedFile.ContentType;
            string[] acceptedTypes = new string[] 
            { 
                "image/bmp", 
                "image/jpeg", 
                "image/tiff", 
                "image/gif", 
                "image/png"
                     };
 
            if (!acceptedTypes.Contains(FileUpload_image.PostedFile.ContentType))
            {
                Alert.Show("This is not image file");
                return;
            }
            Bitmap image = ResizeImage(FileUpload_image.PostedFile.InputStream, 84, 118);
            string imagename = Guid.NewGuid().ToString();
            image.Save(Server.MapPath("~/Pictures/") + imagename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            Img_Employee.ImageUrl = "~/Pictures/" + imagename + ".jpg";
            image_path = "~/Pictures/" + imagename + ".jpg";
        }
 
 
    }
    private Bitmap ResizeImage(Stream streamImage, int maxWidth, int maxHeight)
    {
        Bitmap originalImage = new Bitmap(streamImage);
        int newWidth = originalImage.Width;
        int newHeight = originalImage.Height;
        double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
 
        if (aspectRatio <= 1 && originalImage.Width > maxWidth)
        {
            newWidth = maxWidth;
            newHeight = (int)Math.Round(newWidth / aspectRatio);
        }
        else if (aspectRatio > 1 && originalImage.Height > maxHeight)
        {
            newHeight = maxHeight;
            newWidth = (int)Math.Round(newHeight * aspectRatio);
        }
 
        return new Bitmap(originalImage, newWidth, newHeight);
    }

how to Upload Image or file on FTP in Asp.net using c#

In this web programming tutorial we will learn that how we can Upload Image or file on FTP in Asp.net File Uploader using c#.

copy the below code in your .cs file.

public void ftpfile(string ftpfilepath)
 {
     string ftphost = "your domain name ";
     //here correct hostname or IP of the ftp server to be given  
 
     string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
     FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
     ftp.Credentials = new NetworkCredential("your Domain", "Password");
     //userid and password for the ftp server to given  
 
     ftp.KeepAlive = true;
     ftp.UseBinary = true;
     ftp.Method = WebRequestMethods.Ftp.UploadFile;
      
     // Resize Image is function to resize the image 
     System.Drawing.Image img1 = 
         ResizeImage(FileUpload1.PostedFile.InputStream, 84, 118);
 
     // Convert the image into bytes Array;
     byte[] buffer = ImageToByte(img1);
  
     // Send the image file in form of bytes
     Stream ftpstream = ftp.GetRequestStream();
     ftpstream.Write(buffer, 0, buffer.Length);
     ftpstream.Close();
}

Saturday, May 26, 2012

how to disable right click using jquery

In this web programming tutorial we will learn that how we can prevent right click functionality in browser (this code snipit will work in all browsers).


    
    
    





how to create Tab menu widget using jquery

In this web programming tutorial we will learn that how can use jquery tabs widget using jquery UI.


    
    
    
    

    


    

This is tab one data.

This is tab two data.

This is tab three data.


how to generate image button dynamically in asp.net using c#

In this web programming tutorial we will learn that how we can create an image button dynamically in asp.net using c#. see the below code and put it in your .cs file in page load event.
protected void Page_Load(object sender, EventArgs e)
    {
        ImageButton imgBtn;
        imgBtn = new ImageButton();
        imgBtn.Attributes.Add("onclick", "javascript:return false;");
        imgBtn.ImageUrl = "~/sample.jpg";
        imgBtn.ID = "img_Tooltip";
        imgBtn.ToolTip = "www.web-healer.blogspot.com";
        imgBtn.CssClass = "img_tooltip_Style";
        imgBtn.Height = 50;
        imgBtn.Width = 100;
        form1.Controls.Add(imgBtn);
    }

Thursday, May 24, 2012

how to add text to image in asp.net using c#

In this web programming tutorial we will learn that how we can add some text on an image in asp.net using c#.just copy and page the code and add it in your .cs file.
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System;

public partial class About : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string inputImage = @"E:\color.jpg";
        string outputImageFilePath = @"E:\Resultimage.jpg";
        string textToDisplayOnImage = "www.webhealer.blogspot.com/";

        Bitmap imageInBitMap = new Bitmap(inputImage);
        Graphics imageGraphics = Graphics.FromImage(imageInBitMap);

        //Set the alignment based on the coordinates 
        StringFormat formatAssignment= new StringFormat();
        formatAssignment.Alignment = StringAlignment.Near;
        
        //Here we are going to assign the font color
        Color assignColorToString = System.Drawing.ColorTranslator.FromHtml("#000000");

        //Assigning font size, font family, position of the text to display and others.
        imageGraphics.DrawString(textToDisplayOnImage, new Font("Times new Roman", 8, FontStyle.Bold), new SolidBrush(assignColorToString), new Point(100, 150), formatAssignment);

        //saving in the computer
        imageInBitMap.Save(outputImageFilePath);
    }
}

Monday, May 21, 2012

how to use span tag on a web page using html

In this web programming tutorial we will learn about span tag by using it on a web page using html.

span tag is used to provide an additional structure to an html document. It is used to group and apply style sheet to inline elements of a web page. it can be used to gave characteristics to specific part of other elements.

below is the code example how to use spam tag.

This is a paragraph this is a paragraph this is a paragraph

this is a paragraph

output

This is a paragraph this is a paragraph this is a paragraph

this is a paragraph


how to use div tag on a web page using html

In this web programming tutorial we will learn that how we can use div tag in an html document or in a web page.

div tag is normally used to define a section in an html document or in a web page div tag is a pair tag and must be used a closing tag in order to complete the tag

this is div tag
output
this is div tag

how to use font tag in html

In this web programming tutorial we will learn that how we can use font tag in an html document or in a web page.
 this text is with Verdana font 
 this text is with arial font 
 this text is with helvitica font 
 this text is with impact font 
this text is with Verdana font
this text is with arial font
this text is with helvitica font
this text is with impact font

how to use different format text in html

In this web programming tutorial we will learn that how we can use different type of text format in an web page or in an html document. see the below code.

here is the code to make text bold

in order to make text bold
output:
in order to make text bold

here is the code to make text italic

in order to make text bold
output:
in order to make text Italic

here is the code to make text underline

in order to make text underline
output:
in order to make text underline

here is the code to make text super script

in order to make text Super Script
output:
in order to make text Super Script

here is the code to make text Sub script

in order to make text Sub Script
output:
in order to make text Super Script


how to use horizontal line tag in html

in this web programming tutorial we will learn that how we can use HR tag in an html document or in a web page using html.
 






how to use line break tag using html

In this web programming tutorial we will learn that how we can use Line Break tag in an html document tag.
Line breaks are used to decide where the text will break on a line or continue to the end of the window. it can be used to move the control to the next new line.
see the below code and example syntax of code of line break tag
this is line one<br>

this is line tow<br> 

this is line three<br> 


how to use paragraph tag in html

in this web programming tutorial we will learn that how we can use paragraph tag in an html document or in a web page.

paragraph tag are used in a document to add text in such a way that it will automatically adjust the end of line to suit the window size of the browser.

see the below example of paragraph tag

  

this is paragraph tag


how to use heading tag in html

in this web programming tutorial we will learn that how we can use heading tag heading in a html page.
headings are very important part of any web page. it is used to display different type of heading in HTML document
heading tag is a pair tag, pair tag means every opening tag must have a closing tag.
see the below code of heading tags. it has 6 types as follows

this is heading type 1

this is heading type 2

this is heading type 3

this is heading type 4

this is heading type 5
this is heading type 6
Output

this is heading type 1

this is heading type 2

this is heading type 3

this is heading type 4

this is heading type 5
this is heading type 6

Thursday, May 17, 2012

how to create basic html page

in this web programming tutorial we will learn that how we can create a basic html page. just copy and paste the below code in any editor such as note pad and save the file as test.html. just double click to run the page.

 
   my first page
 
 
     this is body of the page. web-healer.blogspot.com


Sunday, May 13, 2012

How to generate random numbers in asp.net using c#

in this we programming tutorial we will learn that how we can create random number in asp.net using c#. see the below code and just copy and paste.
Random rand = new Random((int)DateTime.Now.Ticks);
        int numIterations = 0;
        numIterations=  rand.Next(1, 100);
        Response.Write(numIterations.ToString());

Wednesday, April 18, 2012

How to sum the value of gridview column in asp.net using jquery and c#

In this web programming tutorial we will learn that how we can SUM the grid view columns values in asp.net using c#.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>




    
    
    


    
Code for .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        grdItems.DataSource = new Item().Items;
        grdItems.DataBind();

    }

}
public class Item
{
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }

    public List Items
    {
        get
        {
            return new List()
                       {
                           new Item(){Name = "Item01",Quantity = 10,Price = 180M},
                           new Item(){Name = "Item01",Quantity = 11,Price = 184M},
                           new Item(){Name = "Item01",Quantity = 12,Price = 190M},
                           new Item(){Name = "Item01",Quantity = 13,Price = 110M},
                       };
        }
    }
}

how to re-write url in asp.net using c#

In this web programming tutorial we will learn that how we can re-write url in asp.net, as it is very important and common and most difficult task for an asp.net developer to re-write url. For URL Rewriting we are using URLRewriter.Net which is available free. Download URLRewriter.Net
Step 1: Download Binary Files for URLRewriter.Net
Step 2: Add Reference to Binary Files, Right click project "Add Reference" and add binary files.
Step 3: Update Web.Config File to make URLRewriter.Net works.


Step 4: Adding Function to Generate SEO Friendly URL from given Title
public static string GenerateURL(object Title, object strId)
{
string strTitle = Title.ToString();

#region Generate SEO Friendly URL based on Title
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');

strTitle = strTitle.ToLower();
char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
strTitle = strTitle.Replace("c#", "C-Sharp");
strTitle = strTitle.Replace("vb.net", "VB-Net");
strTitle = strTitle.Replace("asp.net", "Asp-Net");

//Replace . with - hyphen
strTitle = strTitle.Replace(".", "-");

//Replace Special-Characters
for (int i = 0; i < chars.Length; i++)
{
string strChar = chars.GetValue(i).ToString();
if (strTitle.Contains(strChar))
{
   strTitle = strTitle.Replace(strChar, string.Empty);
}
}

//Replace all spaces with one "-" hyphen
strTitle = strTitle.Replace(" ", "-");

//Replace multiple "-" hyphen with single "-" hyphen.
strTitle = strTitle.Replace("--", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("-----", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("--", "-");

//Run the code again...
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');
#endregion

//Append ID at the end of SEO Friendly URL
strTitle = "~/Article/" + strTitle + "-" + strId + ".aspx";

return strTitle;
}

Step 5: Changing DataBinder.Eval Function in .Aspx Page to reflect changes in URL of Grid.



   
       
                      
       
   
   
       
           
       
   









how to Send Email from Gmail in asp.net using c#

In this web programming tutorial we will learn that how we can send email from Gmail in asp.net using c#, see the below code and just copy and paste.

protected void btnSendEmail_Click(object sender, EventArgs e)
{
//Create Mail Message Object with content that you want to send with mail.
System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("faisalpitafi@gmail.com","israrpatafi@yahoo.com",
"This is the mail subject", "Just wanted to say Hello");

MyMailMessage.IsBodyHtml = false;

//Proper Authentication Details need to be passed when sending email from gmail
System.Net.NetworkCredential mailAuthentication = new
System.Net.NetworkCredential("irfanpitafi@gmail.com", "myPassword");

//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
//For different server like yahoo this details changes and you can
//get it from respective server.
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com",587);

//Enable SSL
mailClient.EnableSsl = true;

mailClient.UseDefaultCredentials = false;

mailClient.Credentials = mailAuthentication;

mailClient.Send(MyMailMessage);
}

how to Disable Multiple Button Click in Asp.net using jquery, javascript and c#

In this web programming tutorial we will learn that How to make a button disable immediately when user clicks it in asp.net so that user cannot click multiple time.




Code for body section


Note: onclick event is calling javascript client-side function and onserverclick event is calling server-side function which performs actual task.
This task can be any as per your logic, for an example I am performing some heavy time consuming task, you can even make use of Threading concept to minimize code.
Server-Side Event to perform actual task
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList a = new ArrayList();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 1000; j++)
{
a.Add(i.ToString() + j.ToString());
}
}
Response.Write("I am done: " +
DateTime.Now.ToLongTimeString());
}

How to enable/disable dropdownlist combobox through a checkbox selection in asp.net using jquery

In this web programming tutorial we will learn that how we can enable/disable dropdownlist control through checkbox selection in asp.net.



    
    
    


    


How to Add copy to clipboard button on page

In this web programming tutorial we will learn how to add or PUT add copy to clip board button functionality on your html or asp.net page copy the below code in your html page.




    

Thursday, April 12, 2012

how to get IP address of visitor using php

In this web programming tutorial we will learn that how we can get or track real (orignal) IP address of visitor of our page.
return !empty($_SERVER['HTTP_CLIENT_IP']) ?
$_SERVER['HTTP_CLIENT_IP'] : (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ?
$_SERVER['HTTP_X_FORWARDED_FOR'] : (!empty($_SERVER['REMOTE_ADDR']) ?
$_SERVER['REMOTE_ADDR'] : null));

Wednesday, April 11, 2012

how to access web method or server side data at client side in asp.net using c#

In this web programming tutorial we will learn that how we can access server side data using Json ajax call at client side using asp.net or php. see the below code and just copy and past in your .aspx or .php file.
function BindPaymentRecord(txnId) { var request = "{'TXN_ID':'" + txnId + "'}"; $.ajax({ type: "POST", url: "Invoice.aspx/BindPaymentDetail", data: request, contentType: "application/json; charset=utf-8", dataType: "json", success: SuccessPaymentRecord }); } function BindChargesRecord(txnId) { var request = "{'TXN_ID':'" + txnId + "'}"; $.ajax({ type: "POST", url: "Invoice.aspx/BindChargesDetail", data: request, contentType: "application/json; charset=utf-8", dataType: "json", success: ChargesSuccessData }); } function SuccessPaymentRecord(data) { document.getElementById('<%=A_Paid.ClientID %>').innerHTML = data.d[0]; document.getElementById('<%=C_ref.ClientID %>').innerHTML = data.d[1]; document.getElementById('<%=C_Bal.ClientID %>').innerHTML = data.d[2]; document.getElementById('<%=Error.ClientID %>').innerHTML = data.d[3]; document.getElementById('<%=P_Method.ClientID %>').innerHTML = data.d[4]; document.getElementById('<%=P_date.ClientID %>').innerHTML = data.d[5]; }

how to generate barcode in asp.net using c#

In this web programming tutorial we will learn that how we can generate barcode in asp.net using c#, as it is often used in different projects and web developers have to face problem, see the below code and just copy and past in your page.
Code for .CS file

using System;
using System.Data;
using System.Drawing.Imaging;
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 Bytescout.BarCode;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Create new barcode
Barcode barcode = new Barcode();

// Set symbology
barcode.Symbology = SymbologyType.Code39;
// Set value
barcode.Value = "Sample";

// Clear http output
Response.Clear();
// Set the content type to PNG
Response.ContentType = "image/png";
// Add content type header
Response.AddHeader("Content-Type", "image/png");
// Set the content disposition
Response.AddHeader("Content-Disposition", "inline;filename=result.png");

// Save image to output stream
barcode.SaveImage(Response.OutputStream, ImageFormat.Png);

// End response
Response.End();

}
}

how to Writing a Text Files Line Counter in asp.net using c#

In this web programming tutorial we will learn that how we can Writing a Text Files Line Counter in asp.net using c#, Bellow is the code, it's so simple that I'm lazy to explain, enjoy:
DirectoryInfo dInfo = new DirectoryInfo(args[0]);
FileInfo[] Files = dInfo.GetFiles("*.php");
int i = 0;
foreach (FileInfo fInfo in Files)
{
  string[] temp = File.ReadAllLines(fInfo.FullName);
  i += temp.Length;
}
Console.WriteLine("Total Lines: " + i);
Console.ReadLine();

Sunday, March 25, 2012

what is a static member of the Class in asp.net using c#


Static Members
One of the tricks about .NET classes is that you really use them in two ways. You can use some
class members without creating an object first. These are called static members, and they’re
accessed by class name.

Foreach loop in asp.net using C#


In this web programming we will learn the use of foreach loop in C#. a foreach loop allows you to loop through the items in a set of data.
With a foreach loop, you don’t need to create an explicit counter variable. Instead, you create
a variable that represents the type of data for which you’re looking. Your code will then loop
until you’ve had a chance to process each piece of data in the set.
Code for .cs file
 string[] strarry = {"One","Two","Three","Four"};
        foreach (string element in strarry)
        {
            System.Diagnostics.Debug.Write(element + " ");
        }


Inner Join in sql quey

In this web programming tutorial we will learn that how we can write sql query for Inner join see the below inner join query,



SELECT *
FROM Products
INNER JOIN Suppliers
ON Products.SupplierID = Suppliers.SupplierID

How to use IF Else Condition to show hide div using Jquery

In this Web Programming tutorial we will learn that how we can use IF and ELSE Condition in Jquery to show or Hide an element on a web form. below is the code:
HTML Button Code:

Below code will check if Div element is hidden than it will make it show else it will nake it hidden.
Code for JQuery:
$('#toggleButton').click(function() {
if ($('#disclaimer').is(':visible')) {
$('#disclaimer').hide();
} else {
$('#disclaimer').show();
}
});

how to hide div on button click using jquery

In this JQuery web programming tutorial we will learn that how we can hide an element on a page using jquery. in this example we will learn that by clicking on a button how we can hide div or any element using jquery.
HTML button

JQuery Code
$('#hideButton').click(function () {
        $('#disclaimer').hide();
    });

how to remove css class from elements using jquery

In this web programming tutorial we will learn that how we can remove css class on some elements here is the way using jquery
$('#celebs tr.test').removeClass('test');

how to add or replace css class on using jquery

In this web Programming tutorial we will learn that how we can replace or Add a css Class to take effect on a specific table's row using jquery, Css Class we want to replace

.test {
background-color: #dddddd;
color: #666666;
}
Jquery Code to replace the class


above code will find the table with ID "celebs" and replace the above css class named "test" to all even Table rows using jquery.

how to change Row back ground color and text color using jquery

In this web programming tutorial we will learn that how we can change the background color and text color of Table's alternate rows ie we want that Every "Even" Row's text color and background color of a table should changed using Jquery, see the below code,

test
test
test
test
test
Jquery Code to affect all rows in a table


Thursday, March 22, 2012

how to reverse a string in asp.net using c#

In this web Programming tutorial we will learn that how we can print a string in reverse mode in asp.net using c#,
for example you have a string as below
string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
and you want to print or show it in Reverse mode as below, Output: ZYXWVUTSRQPONMLKJIHGFEDCBA here is the code you can use in ur .cs file and can use as per your requirement. function call.
 string teest = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        test.Text = Reverse(teest);
actual function defination
     public string Reverse(string str)
         {
              int len = str.Length;
              char[] arr = new char[len];

                for (int i = 0; i < len; i++)
                {
                    arr[i] = str[len - 1 - i];
                }

                    return new string(arr);
         }

Wednesday, March 21, 2012

how to create image button dynamically in asp.net using c#

In this web programming tutorial we will learn that how we can creat a image button dynamically in asp.net using c#.
See the below code for your .cs file
in my case i have created a print button you may create a button as per your requirements.
ImageButton imgButton = new ImageButton();
                        imgButton.ID = "img1";
                        imgButton.CausesValidation = false;
                        imgButton.ImageUrl = "../img/printer_icon.gif";
                        string targeturl = "http://localhost:8000" + Request.RawUrl.ToString();
                        //imgButton.OnClientClick = "javascript:return OpenNewWindow('" + targeturl + "')";
                        imgButton.Click += new ImageClickEventHandler(ImageButton1_Click);
                        imgButton.ToolTip = "Print";
                        cc.Controls.Add(imgButton);

how to format amount (Moany) in asp.net using c#

In this web Programming tutorial we will learn that how we can format a string to Monay type. see the below code in asp.net using c#.
Code for .cs file
Total_amount.Text = string.Format("{0:###,###,##0.00}", Total_Amountdue);

Saturday, March 17, 2012

what is LINQ

LINQ (Language Integrated Query) is a set of extensions for the C# and Visual Basic languages. It allows
you to write C# or Visual Basic code that manipulates in-memory data in much the same way you query
a database.
Technically, LINQ defines about 40 query operators, such as select, from, in, where, and orderby (in
C#). These operators allow you to code your query. However, there are various types of data on which
this query can be performed, and each type of data requires a separate flavor of LINQ.
The most fundamental LINQ flavor is LINQ to Objects, which allows you to take a collection of
objects and perform a query that extracts some of the details from some of the objects. LINQ to Objects isn’t ASP.NET-specific. In other words, you can use it in a web page in exactly the same way that you use it in any other type of .NET application.
Along with LINQ to Objects is LINQ to DataSet, which provides similar behavior for querying an inmemory DataSet object, and LINQ to XML, which works on XML data. But one of the most interesting flavors of LINQ is LINQ to Entities, which allows you to use the LINQ syntax to execute a query against a relational database. Essentially, LINQ to Entities creates a properly parameterized SQL query based on your code, and executes the query when you attempt to access the query results. You don’t need to write any data access code or use the traditional ADO.NET objects. LINQ to Objects, LINQ to DataSet, and LINQ to XML are features that complement ASP.NET, and aren’t bound to it in any specific way. However, ASP.NET includes enhanced support for LINQ to Entities, including a data source control that lets you perform a query through LINQ to Entities and bind the results to a web control, with no extra code required.

Friday, March 16, 2012

how to save and fetch images from sql server in asp.net using c#

in previous article we explained that how to save files in sql server database using asp.net now we will learn that how to fetch images from sql server database in asp.net using c#

below function in page load event will just fetch the image data from sql server.
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["ImageID"] != null)
    {
        string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value
        = Convert.ToInt32 (Request.QueryString["ImageID"]);
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = dt.Rows[0]["ContentType"].ToString();
            Response.AddHeader("content-disposition", "attachment;filename="
            + dt.Rows[0]["Name"].ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
}
and we wll pass the parameters to our image tag as mention below in asp.net



how to save and fetch Files from SQL Server Database in ASP.Net using c#

In this web programming tutorial we will learn that how we can save files in sql server database and how we can fetch or retrieve saved files from sql server database in asp.net using c#.

Below is the table structure in order to save files

here is the connection string that will be used to connect to database



now here we need to read the file using file Stream and then File Stream will be converted into byte array using BinaryReader in order to save into the database.
// Read the file and convert it to Byte Array
string filePath = Server.MapPath("APP_DATA/TestDoc.docx");
string filename = Path.GetFileName(filePath);
 
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();

after reading the file we need to save it into database by using following command
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
Below function InsertUpdateData accepts the SqlCommand object, executes the query and inserts the data into the database and thats it our file will be saved into database.
private Boolean InsertUpdateData(SqlCommand cmd)
{
    String strConnString = System.Configuration.ConfigurationManager
    .ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        cmd.ExecuteNonQuery();
        return true;
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        return false;
    }
    finally
    {
        con.Close();
        con.Dispose();
    }
}
Now we need to fetch the data and need to display. In order to do so web need to write a select command to fetch the data from sql server database table.
string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
DataTable dt = GetData(cmd);
if (dt != null)
{
    download(dt);
}
below function will simply execute select statement in sqlserver query window.
private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    String strConnString = System.Configuration.ConfigurationManager
    .ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        return dt;
    }
    catch
    {
        return null;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}
Here is the function which initiates the download of file. It basically reads the file contents into a Byte array and also gets the file name and the Content Type. Then it writes the bytes to the response using Response.BinaryWrite
private void download (DataTable dt)
{
    Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = dt.Rows[0]["ContentType"].ToString();
    Response.AddHeader("content-disposition", "attachment;filename="
    + dt.Rows[0]["Name"].ToString());
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}

how to calculate total rows and subtotal in asp.net gridview using jquery

In this web programming tutorial we will learn that how we can calculate the row total and subtotal of gridview using jquery.


    
        
        
        
            
                
            
        
        
            
                
            
        
    

Grand Total:

below jquery script will help us to perform all calculations in grid view rows.



how to maintain scroll position of the page after postback in asp.net using javascript

In this web programming tutorial we will learn that how we can maintain scroll position of the page when page is postback. although asp.net framework provides us MaintainScrollPositionOnPostback but it has been observed that it is not working in Firefox and Chrome browsers. So in order to over come this flaw we have develop below javascript it is working fine in all major browsers.

how to convert text string into an image in asp.net using c#

in this web programming tutorial we will learn that how we can convert text string provided by user into an image in asp.net using c#. this will help us to make our own captcha images instead to use third party tools.

HTML Code to get text string from user


    


    

we need to inherit following namespaces in our .cs file
using System.Drawing.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
Now below code will help us to genereate .jpg file from user input string.
protected void btnConvert_Click(object sender, EventArgs e)
{
    string text = txtText.Text.Trim();
    Bitmap bitmap = new Bitmap(1, 1);
    Font font = new Font("Arial", 25, FontStyle.Regular, GraphicsUnit.Pixel);
    Graphics graphics = Graphics.FromImage(bitmap);
    int width = (int)graphics.MeasureString(text, font).Width;
    int height = (int)graphics.MeasureString(text, font).Height;
    bitmap = new Bitmap(bitmap, new Size(width, height));
    graphics = Graphics.FromImage(bitmap);
    graphics.Clear(Color.White);
    graphics.SmoothingMode = SmoothingMode.AntiAlias;
    graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
    graphics.DrawString(text, font, new SolidBrush(Color.FromArgb(255, 0, 0)), 0, 0);
    graphics.Flush();
    graphics.Dispose();
    string fileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".jpg";
    bitmap.Save(Server.MapPath("~/images/") + fileName, ImageFormat.Jpeg);
    imgText.ImageUrl = "~/images/" + fileName;
    imgText.Visible = true;
}

how to use ASP.Net CompareValidator to compare dates in dd/mm/yyyy format

in this web programming tutorial we will learn that how to use ASP.Net CompareValidator to compare dates in dd/mm/yyyy format.

By default the ASP.Net CompareValidator does not work for dd/mm/yyyy format hence we will need to change the Culture property of the page to en-GB in the @Pagedirective of the ASP.Net Web Page as show below

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Culture = "en-GB" %>
 

 


    


    
Start Date:   End Date:

how to Export data into Text/CSV file from grid view in asp.net using c#

To export the GridView as CSV, I am running a two for loops. While looping through the GridView columns and appending comma after each column and while looping through rows appending new line character. Refer the code below.
protected void btnExportCSV_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.csv");
    Response.Charset = "";
    Response.ContentType = "application/text";
 
    GridView1.AllowPaging = false;
    GridView1.DataBind();
 
    StringBuilder sb = new StringBuilder();
    for (int k = 0; k < GridView1.Columns.Count; k++)
    {
        //add separator
        sb.Append(GridView1.Columns[k].HeaderText + ',');
    }
    //append new line
    sb.Append("\r\n");
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            //add separator
            sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
        }
        //append new line
        sb.Append("\r\n");
    }
    Response.Output.Write(sb.ToString());
    Response.Flush();
    Response.End();
}
To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

how to export data into excel file from grid view in asp.net using c#

In this web programming tutorial we will learn that how we can export grid view data into a pdf file in asp.net using c#.

For exporting the GridView to PDF I am using the iTextSharp Library. You will need to Add Reference for the iTextSharp Library in your Website.


Then import the following Namespaces

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
code for .cs file

By default the iTextSharp Library does not support background color of table cells or table rows

Hence when you render it as PDF your GridView is rendered without any formatting.

Recently I read an article on hamang.net where the author has provided the snippet to modify the iTextSharp so that it exports the HTML with background color.



For this tutorial, I have already modified the iTextSharp Library DLL so that the GridView is rendered with all the background color used. You can refer the code for exporting GridView to PDF below

protected void btnExportPDF_Click(object sender, EventArgs e)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f,10f,10f,0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End(); 
}

To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

how to export grid view data into MS excel file in asp.net using c#

In this web programming tutorial we will learn that how we can export grid view data into MS excel file in asp.net using c#

Code for .cs file
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
 
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
 
GridView1.AllowPaging = false;
GridView1.DataBind();
 
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
 
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");  
 
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
    GridViewRow row = GridView1.Rows[i];
 
    //Change Color back to white
    row.BackColor = System.Drawing.Color.White;
 
    //Apply text style to each Row
    row.Attributes.Add("class", "textmode");
 
    //Apply style to Individual Cells of Alternating Row
    if (i % 2 != 0)
    {
        row.Cells[0].Style.Add("background-color", "#C2D69B");
        row.Cells[1].Style.Add("background-color", "#C2D69B");
        row.Cells[2].Style.Add("background-color", "#C2D69B");
        row.Cells[3].Style.Add("background-color", "#C2D69B");  
    }
}
GridView1.RenderControl(hw);
 
//style to format numbers to string
string style = @"";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

how to export data into MS Word File from grid view in asp.net using c#

In this web programming tutorial we will learn that how we can export data into MS word file from grid view by clicking a button in asp.net using c#
Code for .aspx file

   
    
    
    
    
   

Code for .CS file
protected void btnExportWord_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
    "attachment;filename=GridViewExport.doc");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-word ";
    StringWriter sw= new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

Thursday, March 15, 2012

how to validate image at client side in asp.net

In this web Programming tutorial we will learn that how we can validate the image at client side before uploading it that it is according to our required format i.e. png, jpg or bmp.

 Upload a valid image;

how to re size the image while uploading in asp.net using c#

In this web programming tutorial we will learn that how can we resize the image while uploading to the server as per our requirements.
code for .cs file
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.Drawing;  
using System.Drawing.Drawing2D;  
using System.Drawing.Imaging;  
using System.IO;  
///   
/// Summary description for clsImageUpload : Credits : http://prajeeshkk.blogspot.com  
///   
public class clsImageUpload  
{  
string fileName;  
public clsImageUpload()  
{  
//  
// TODO: Add constructor logic here  
//  
}  
//This function is called from aspnet page, it takes directory name as parameter  
public string HandleUploadedFile(string directory)  
{  
// To get the root of the web site  
string root = HttpContext.Current.Server.MapPath("~/");  
// clean up the path  
if (!root.EndsWith(@"\"))  
root += @"\";  
// make a folder to store the images in  
string fileDirectory = root + @"\" + directory + "\\";  
// create the folder if it does not exist  
// make a link to the new file  
  
// loop through the file in the request  
for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)  
{  
// get the file instance  
HttpPostedFile fi = HttpContext.Current.Request.Files.Get(i);  
// create a byte array to store the file bytes  
byte[] fileBytes = new byte[fi.ContentLength];  
// fill the byte array  
using (System.IO.Stream stream = fi.InputStream)  
{  
stream.Read(fileBytes, 0, fi.ContentLength);  
}  
// create a random file name  
fileName = Guid.NewGuid().ToString();  
  
// write the resized file to the file system  
File.WriteAllBytes(fileDirectory + fileName + "_thumb.jpg", ResizeImageFile(fileBytes, 75));  
fileBytes = null;  
}  
return (fileName + "_thumb.jpg");  
}  
public void HandleUploadedFileUseExistingName(string directory, string fname)  
{  
// get the root of the web site  
string root = HttpContext.Current.Server.MapPath("~/");  
// clean up the path  
if (!root.EndsWith(@"\"))  
root += @"\";  
// make a folder to store the images in  
string fileDirectory = root + @"\" + directory + "\\";  
// loop through the file in the request  
for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)  
{  
// get the file instance  
HttpPostedFile fi = HttpContext.Current.Request.Files.Get(i);  
// create a byte array to store the file bytes  
byte[] fileBytes = new byte[fi.ContentLength];  
// fill the byte array  
using (System.IO.Stream stream = fi.InputStream)  
{  
stream.Read(fileBytes, 0, fi.ContentLength);  
}  
// create a random file name  
fileName = fname;  
// write the resized file to the file system  
File.WriteAllBytes(fileDirectory + fileName, ResizeImageFile(fileBytes, 75));  
fileBytes = null;  
}  
}  
/// This fuction returns a Byte array containing the resized file  
private static byte[] ResizeImageFile(byte[] imageFile, int targetSize)  
{  
using (System.Drawing.Image oldImage =  
System.Drawing.Image.FromStream(new MemoryStream(imageFile)))  
{  
//If you want to maintain the propotion use following code  
//Size newSize = CalculateDimensions(oldImage.Size, targetSize);  
//If you want to use a fixed size use following one  
Size newSize = GetDimension();  
using (Bitmap newImage =  
new Bitmap(newSize.Width,  
newSize.Height, PixelFormat.Format24bppRgb))  
{  
using (Graphics canvas = Graphics.FromImage(newImage))  
{  
canvas.SmoothingMode = SmoothingMode.AntiAlias;  
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;  
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;  
canvas.DrawImage(oldImage,  
new Rectangle(new Point(0, 0), newSize));  
MemoryStream m = new MemoryStream();  
newImage.Save(m, ImageFormat.Jpeg);  
return m.GetBuffer();  
}  
}  
}  
}  
/// This function Calculates the new size of the image based on the target size  
private static Size CalculateDimensions(Size oldSize, int targetSize)  
{  
Size newSize = new Size();  
if (oldSize.Height > oldSize.Width)  
{  
newSize.Width =  
(int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));  
newSize.Height = targetSize;  
}  
else  
{  
newSize.Width = targetSize;  
newSize.Height =  
(int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));  
}  
return newSize;  
}  
//Dimension of the images can be set here  
private static Size GetDimension()  
{  
Size newSize = new Size();  
newSize.Width = 100;  
newSize.Height = 100;  
return newSize;  
}  
}