Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
4

Ajax AutoCompleteExtender In Master Page Asp.Net

This Example shows How To Use Ajax AutoCompleteExtender TextBox In Master Page In Asp.Net.

Open Visual Studio and create new website, add master page in it and design it as you want.

Create a BIN folder in application and add AjaxControlToolkit.dll in it.

I have use Northwind database to fetch names for AutoCompletion list.

Add Connection String in web.config file

<connectionStrings>
<add name="NorthwindConnectionString" 
     connectionString="Data Source=AMITJAIN\SQL;
                       Initial Catalog=Northwind;
                       User ID=amit;Password=password"
providerName="System.Data.SqlClient"/>
</connectionStrings>


Place ToolkitScriptManager on Master Page inside form tag, one textbox and Add Ajax AutoComplete Extender from Toolbox.

HTML SOURCE OF MASTER PAGE
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
 
<asp:TextBox ID="txtAutoComplete" runat="server"/>
                               
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" 
                          runat="server" 
                          DelimiterCharacters="" 
                          Enabled="True" 
                          ServicePath="~/AutoComplete.asmx" 
                          ServiceMethod="GetCompletionList"
                          TargetControlID="txtAutoComplete"
                          MinimumPrefixLength="1" 
                          CompletionInterval="10" 
                          EnableCaching="true"
                          CompletionSetCount="12">
</asp:AutoCompleteExtender>
                
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
 
</form>
</body>
</html>


We can set CompletionList WIdth and styles using CSS or use AutoCompleteExtender In GridView or Windows Forms Application.

Add new webservice, name it AutoComplete.asmx and write following code in it's code behind.

C#
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService {

    public AutoComplete () 
    {
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        if (count == 0)
        {
            count = 10;
        }
        DataTable dt = GetRecords(prefixText);
        List items = new List(count);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strName = dt.Rows[i][0].ToString();
            items.Add(strName);
        }
        return items.ToArray();
    }

    public DataTable GetRecords(string strName)
    {
        string strConn = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue("@Name", strName);
        cmd.CommandText = "Select FirstName from Employees where FirstName like '%'+@Name+'%'";
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        return objDs.Tables[0];
    }
}

VB.NET
Imports System.Collections.Generic
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration

 _
 _
 _
Public Class AutoComplete
 Inherits System.Web.Services.WebService

 Public Sub New()
 End Sub

  _
 Public Function GetCompletionList(prefixText As String, count As Integer) As String()
  If count = 0 Then
   count = 10
  End If
  Dim dt As DataTable = GetRecords(prefixText)
  Dim items As New List(Of String)(count)

  For i As Integer = 0 To dt.Rows.Count - 1
   Dim strName As String = dt.Rows(i)(0).ToString()
   items.Add(strName)
  Next
  Return items.ToArray()
 End Function

 Public Function GetRecords(strName As String) As DataTable
  Dim strConn As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
  Dim con As New SqlConnection(strConn)
  Dim cmd As New SqlCommand()
  cmd.Connection = con
  cmd.CommandType = System.Data.CommandType.Text
  cmd.Parameters.AddWithValue("@Name", strName)
  cmd.CommandText = "Select FirstName from Employees where FirstName like '%'+@Name+'%'"
  Dim objDs As New DataSet()
  Dim dAdapter As New SqlDataAdapter()
  dAdapter.SelectCommand = cmd
  con.Open()
  dAdapter.Fill(objDs)
  con.Close()
  Return objDs.Tables(0)
 End Function
End Class


Build and run the application.

7

Asp.Net AjaxFileUpload Control With Drag Drop And Progress Bar

This Example explains how to use AjaxFileUpload Control With Drag Drop And Progress Bar Functionality In Asp.Net 2.0 3.5 4.0 C# And VB.NET.

May 2012 release of AjaxControlToolkit includes a new AjaxFileUpload Control which supports Multiple File Upload, Progress Bar and Drag And Drop functionality.

These new features are supported by Google Chrome version 16+, Firefox 8+ , Safari 5+ and Internet explorer 10 + , IE9 or earlier does not support this feature.

AjaxFileUpload Control Example with Drag Drop And Progress Bar

To start with it, download and put latest AjaxControlToolkit.dll in Bin folder of application, Place ToolkitScriptManager and AjaxFileUpload on the page.

HTML SOURCE
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
          
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" 
                    OnUploadComplete="UploadComplete" 
                    ThrobberID="loader"/>
 
<asp:Image ID="loader" runat="server" 
           ImageUrl ="~/loading.gif" Style="display:None"/>


ThrobberID is used to display loading image instead of progress bar in unsupported browsers.

Type of files uploaded can be restricted by using AllowedFileTypes property with comma separated list such as "zip,doc,pdf".

Write following code in OnUploadComplete event to save the file.

C#
protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }
VB.NET
protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }
Build and run the code.

Download Sample Code


2

Cascading ComboBox In Winforms Windows Forms C# VB.NET

This example explains How To Create Cascading ComboBox Dependent On One Another In WinForms Windows Forms Applications Using C# And VB.Net.


I have used Country, State, City tables from database to populate respective cascading combobox based on selection of country and state.


Drag 3 combobox controls from toolbar on the windows form, write following code to populate comboboxes.

Table schemas are shown below.

Cascading Combobox In Winforms Windows Forms C# VB



Write connection string in app.config file
<configuration>
<connectionStrings>
<add name="connectionString"
     connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Cascading.mdf;Integrated Security=True;User Instance=True"
     providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>


Bind Country ComboBox when Form loads
using System;
using System.Data;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace CascadingComboBox
{
    public partial class Form1 : Form
    {
        string strConn = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FillCountry();
        }
        private void FillCountry()
        {
            SqlConnection con = new SqlConnection(strConn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT CountryID, CountryName FROM Country";
            DataSet objDs = new DataSet();
            SqlDataAdapter dAdapter = new SqlDataAdapter();
            dAdapter.SelectCommand = cmd;
            con.Open();
            dAdapter.Fill(objDs);
            con.Close();
            cmbCountry.ValueMember = "CountryID";
            cmbCountry.DisplayMember = "CountryName";
            cmbCountry.DataSource = objDs.Tables[0];
        }
    }
}


Populate State and City combobox in SelectedIndexChanged event of country,State combobox based on selected IDs
private void cmbCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCountry.SelectedValue.ToString() != "")
            {
                int CountryID = Convert.ToInt32(cmbCountry.SelectedValue.ToString());
                FillStates(CountryID);
                cmbCity.SelectedIndex = 0;
            }
        }

        private void FillStates(int countryID)
        {
            SqlConnection con = new SqlConnection(strConn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID";
            cmd.Parameters.AddWithValue("@CountryID", countryID);
            DataSet objDs = new DataSet();
            SqlDataAdapter dAdapter = new SqlDataAdapter();
            dAdapter.SelectCommand = cmd;
            con.Open();
            dAdapter.Fill(objDs);
            con.Close();
            if (objDs.Tables[0].Rows.Count > 0)
            {
                cmbState.ValueMember = "StateID";
                cmbState.DisplayMember = "StateName";
                cmbState.DataSource = objDs.Tables[0];
            }
            
        }

        private void cmbState_SelectedIndexChanged(object sender, EventArgs e)
        {
            int StateID = Convert.ToInt32(cmbState.SelectedValue.ToString());
            FillCities(StateID);
        }

        private void FillCities(int stateID)
        {
            SqlConnection con = new SqlConnection(strConn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID";
            cmd.Parameters.AddWithValue("@StateID", stateID);
            DataSet objDs = new DataSet();
            SqlDataAdapter dAdapter = new SqlDataAdapter();
            dAdapter.SelectCommand = cmd;
            con.Open();
            dAdapter.Fill(objDs);
            con.Close();
            if (objDs.Tables[0].Rows.Count > 0)
            {
                cmbCity.DataSource = objDs.Tables[0];
                cmbCity.DisplayMember = "CityName";
                cmbCity.ValueMember = "CItyID";

            }

        }


VB.NET CODE
Private Sub Form1_Load(sender As Object, e As EventArgs)
 FillCountry()
End Sub
Private Sub FillCountry()
 Dim con As New SqlConnection(strConn)
 Dim cmd As New SqlCommand()
 cmd.Connection = con
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "SELECT CountryID, CountryName FROM Country"
 Dim objDs As New DataSet()
 Dim dAdapter As New SqlDataAdapter()
 dAdapter.SelectCommand = cmd
 con.Open()
 dAdapter.Fill(objDs)
 con.Close()
 cmbCountry.ValueMember = "CountryID"
 cmbCountry.DisplayMember = "CountryName"
 cmbCountry.DataSource = objDs.Tables(0)
End Sub

Private Sub cmbCountry_SelectedIndexChanged(sender As Object, e As EventArgs)
 If cmbCountry.SelectedValue.ToString() <> "" Then
  Dim CountryID As Integer = Convert.ToInt32(cmbCountry.SelectedValue.ToString())
  FillStates(CountryID)
  cmbCity.SelectedIndex = 0
 End If
End Sub

Private Sub FillStates(countryID As Integer)
 Dim con As New SqlConnection(strConn)
 Dim cmd As New SqlCommand()
 cmd.Connection = con
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"
 cmd.Parameters.AddWithValue("@CountryID", countryID)
 Dim objDs As New DataSet()
 Dim dAdapter As New SqlDataAdapter()
 dAdapter.SelectCommand = cmd
 con.Open()
 dAdapter.Fill(objDs)
 con.Close()
 If objDs.Tables(0).Rows.Count > 0 Then
  cmbState.ValueMember = "StateID"
  cmbState.DisplayMember = "StateName"
  cmbState.DataSource = objDs.Tables(0)
 End If

End Sub

Private Sub cmbState_SelectedIndexChanged(sender As Object, e As EventArgs)
 Dim StateID As Integer = Convert.ToInt32(cmbState.SelectedValue.ToString())
 FillCities(StateID)
End Sub

Private Sub FillCities(stateID As Integer)
 Dim con As New SqlConnection(strConn)
 Dim cmd As New SqlCommand()
 cmd.Connection = con
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID"
 cmd.Parameters.AddWithValue("@StateID", stateID)
 Dim objDs As New DataSet()
 Dim dAdapter As New SqlDataAdapter()
 dAdapter.SelectCommand = cmd
 con.Open()
 dAdapter.Fill(objDs)
 con.Close()
 If objDs.Tables(0).Rows.Count > 0 Then
  cmbCity.DataSource = objDs.Tables(0)
  cmbCity.DisplayMember = "CityName"

  cmbCity.ValueMember = "CItyID"
 End If

End Sub


Build and run the application.

ComboBox In Winforms C# VB.NET Cascading Dependent on one another


Download Sample Code


4

Drag Drop GridView Rows With JQuery Asp.Net

This Example explains How To Implement Drag And Drop GridView Rows Functionality Using JQuery JavaScript In Asp.Net 2.0 3.5 4.0 To Rearrange Row On Client Side.

You need to download and add JQuery and TableDnD plugin in your application.

GridView is populated with Northwind database using SqlDataSource.

Drag Drop Gridview Rows Using JQuery


Add Script references and css style in head section of page.

   1:  <style type="text/css">
   2:     .highlight
   3:      {
   4:          color : White !important;
   5:          background-color : Teal !important;
   6:      }
   7:  </style>
   8:  <script src="jquery-1.7.1.js" type="text/javascript"/>
   9:  <script src="jquery.tablednd.0.7.min.js" type="text/javascript"/>

Call tableDnD function of drag and drop plugin by passing Gridview Id.

   1:  <script type="text/javascript" language="javascript">
   2:  $(document).ready(function() 
   3:  {
   4:  $("#<%=GridView1.ClientID%>").tableDnD(
   5:              {
   6:                  onDragClass: "highlight"
   7:              });
   8:  });
   9:  </script>
  10:  </head>

   1:  <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
   2:                AutoGenerateColumns="False" DataKeyNames="OrderID" 
   3:                DataSourceID="SqlDataSource1">
   4:  <Columns>
   5:  <asp:BoundField DataField="OrderID" HeaderText="OrderID"/>
   6:  <asp:BoundField DataField="Freight" HeaderText="Freight"/>
   7:  <asp:BoundField DataField="ShipName" HeaderText="ShipName"/>
   8:  <asp:BoundField DataField="ShipCity" HeaderText="ShipCity"/>
   9:  <asp:BoundField DataField="ShipCountry" HeaderText="ShipCountry"/>
  10:  </Columns>
  11:  </asp:GridView>

Build and run the code.

1

Create Add Dynamic Button Controls In Asp.Net Handle Click Event

This example explains how to Create or Add Dynamic Controls or Button In Asp.Net page and handle respective events like Click Event.

I am creating one button and Label dynamically and setting Label text property in Click Event.
I have used Style property to place the control on exact position or location on page.

Object of control must be declared globally to be available in all events of page, and should be created and added to form in Page_Init event, properties such as Text should be assigned in Page_Load.

C# CODE

using System;
using System.Web.UI.WebControls;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    Button btnDyn;
    Label lbl;
    protected void Page_Init(object sender, EventArgs e)
    {
        btnDyn = new Button();
        btnDyn.ID = "btnDyn";
        btnDyn.Style["Position"] = "Absolute";
        btnDyn.Style["Top"] = "100px";
        btnDyn.Style["Left"] = "10px";
        btnDyn.Click += new EventHandler(Button_Click);
        this.form1.Controls.Add(btnDyn);

        lbl = new Label();
        lbl.ID = "lblDyn";
        lbl.Style["Position"] = "Absolute";
        lbl.Style["Top"] = "150px";
        lbl.Style["Left"] = "10px";
        this.form1.Controls.Add(lbl);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        btnDyn.Text = "Dynamic Button";
        lbl.Text = "";
    }

    protected void Button_Click(object sender, EventArgs e)
    {
        lbl.Text = "dynamic label text";
    }
}

VB.NET

Imports System.Web.UI.WebControls
Imports System.IO

Public Partial Class _Default
 Inherits System.Web.UI.Page
 Private btnDyn As Button
 Private lbl As Label
 Protected Sub Page_Init(sender As Object, e As EventArgs)
  btnDyn = New Button()
  btnDyn.ID = "btnDyn"
  btnDyn.Style("Position") = "Absolute"
  btnDyn.Style("Top") = "100px"
  btnDyn.Style("Left") = "10px"
  AddHandler btnDyn.Click, New EventHandler(AddressOf Button_Click)
  Me.form1.Controls.Add(btnDyn)

  lbl = New Label()
  lbl.ID = "lblDyn"
  lbl.Style("Position") = "Absolute"
  lbl.Style("Top") = "150px"
  lbl.Style("Left") = "10px"
  Me.form1.Controls.Add(lbl)
 End Sub
 Protected Sub Page_Load(sender As Object, e As EventArgs)
  btnDyn.Text = "Dynamic Button"
  lbl.Text = ""
 End Sub

 Protected Sub Button_Click(sender As Object, e As EventArgs)
  lbl.Text = "dynamic label text"
 End Sub
End Class

This is how we can create dynamic controls in asp.net or add controls dynamically on aspx page.

1

Download Multiple Files As Zip File Archive In Asp.Net

This Example Explains How To Download Multiple Files As Zip File Archive From Server In Asp.Net.

I have placed one CheckBoxList on asp.net page to Display Files From Server And One button to Download Zip File Archives.

I have used DotNetZip Library to Create Zip File from selected file(s), Add Ionic.Zip.dll in Bin folder in application root.
Download Multiple files As Zip FIle In Asp.Net

HTML SOURCE OF PAGE
   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <asp:CheckBoxList ID="checkBoxList" runat="server"/>
   4:   
   5:  <asp:Button ID="btnDownload" runat="server" 
   6:              onclick="btnDownload_Click" 
   7:              Text="Download Files" />
   8:  </div>
   9:  </form>

C# CODE
using System;
using System.Web.UI.WebControls;
using System.IO;
using Ionic.Zip;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/csharpdotnetfreak.blogspot.com"));
            FileInfo[] filesInFolder = directory.GetFiles("*.*", SearchOption.AllDirectories);
            foreach (FileInfo fileInfo in filesInFolder)
            {
                checkBoxList.Items.Add(fileInfo.Name);
            }
        }

    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        ZipFile multipleFiles = new ZipFile();
        Response.AddHeader("Content-Disposition", "attachment; filename=DownloadedFile.zip");
        Response.ContentType = "application/zip";
        foreach (ListItem fileName in checkBoxList.Items)
        {
            if (fileName.Selected)
            {
                string filePath = Server.MapPath("~/csharpdotnetfreak.blogspot.com" + fileName.Value);
                multipleFiles.AddFile(filePath,string.Empty);
            }
        }
        multipleFiles.Save(Response.OutputStream);
    }
}

VB.NET
Imports System.Web.UI.WebControls
Imports System.IO
Imports Ionic.Zip

Public Partial Class _Default
 Inherits System.Web.UI.Page
 Protected Sub Page_Load(sender As Object, e As EventArgs)
  If Not IsPostBack Then
   Dim directory As New DirectoryInfo(Server.MapPath("~/csharpdotnetfreak.blogspot.com"))
   Dim filesInFolder As FileInfo() = directory.GetFiles("*.*", SearchOption.AllDirectories)
   For Each fileInfo As FileInfo In filesInFolder
    checkBoxList.Items.Add(fileInfo.Name)
   Next
  End If

 End Sub
 Protected Sub btnDownload_Click(sender As Object, e As EventArgs)
  Dim multipleFiles As New ZipFile()
  Response.AddHeader("Content-Disposition", "attachment; filename=DownloadedFile.zip")
  Response.ContentType = "application/zip"
  For Each fileName As ListItem In checkBoxList.Items
   If fileName.Selected Then
    Dim filePath As String = Server.MapPath("~/csharpdotnetfreak.blogspot.com" & fileName.Value)
    multipleFiles.AddFile(filePath, String.Empty)
   End If
  Next
  multipleFiles.Save(Response.OutputStream)
 End Sub
End Class


Download Sample Code


6

Print GridView Data In Asp.Net Using C# VB JavaScript

To Print GridView Data In Asp.Net Using C# And VB.NET, I have placed GridView inside a Div and this Div will be called for printing using javascript.

Print window will be opened in onclick event of Button. Javascript to print data is written in Page Load event of page and registered with RegisterStartupScript.

Print GridView Data In Asp.Net C# VB

HTML SOURCE OF GRIDVIEW
   1:  <div id="gvDiv">
   2:   
   3:  <asp:GridView ID="gvPrint" runat="server" 
   4:                DataSourceID="SqlDataSource1">
   5:  <Columns>
   6:  <asp:BoundField DataField="CategoryID" 
   7:                  HeaderText="CategoryID"/>
   8:  <asp:BoundField DataField="CategoryName" 
   9:                  HeaderText="CategoryName"/>
  10:  </Columns>
  11:  </asp:GridView>
  12:  </div>
  13:     
  14:  <asp:Button ID="btnPrint" runat="server" 
  15:              Text="Print Data"/>

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        string printScript =
        @"function PrintGridView()
         {
            var gridInsideDiv = document.getElementById('gvDiv');
            var printWindow = window.open('gview.htm','PrintWindow','letf=0,top=0,width=150,height=300,toolbar=1,scrollbars=1,status=1');
            printWindow.document.write(gridInsideDiv.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();}";
        this.ClientScript.RegisterStartupScript(Page.GetType(), "PrintGridView", printScript.ToString(), true);
        btnPrint.Attributes.Add("onclick", "PrintGridView();");       
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim printScript As String = "function PrintGridView()
         {
            var gridInsideDiv = document.getElementById('gvDiv');
            var printWindow = window.open('gv.htm','PrintWindow','letf=0,top=0,width=150,height=300,toolbar=1,scrollbars=1,status=1');
            printWindow.document.write(gridInsideDiv.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();}"
 Me.ClientScript.RegisterStartupScript(Page.[GetType](), "PrintGridView", printScript.ToString(), True)
 btnPrint.Attributes.Add("onclick", "PrintGridView();")
End Sub


1

Upload Unzip Extract Zip Files Archive In Asp.Net

This example explains how to Upload And Unzip Or Extract Zip Files Archive In Asp.Net to a Server Directory Folder then display extracted files in Gridview using C# VB.NET.

I'm using DotNetZip library for extracting zip archives, you need to putIonic.Zip.dll in BIN folder of your application.

Place one FileUpload control and Button on page to upload files, we will Upload and unzip in Click Event of Button using ExtractAll method of ZipFile object.

Place one GridView on page to Display files after extraction to a folder or directory on server.

You can Delete uploaded file from server once unzipped.

Upload and Extract Zip Files Archive on server in asp.net

HTML SOURCE OF PAGE
   1:  <asp:FileUpload ID="fileUpload1" runat="server"/>
   2:  <asp:Button ID="btnExtract" runat="server" 
   3:              onclick="btnExtract_Click" 
   4:              Text="Upload Zip Files" />
   5:      
   6:  <asp:Label ID="lblMessage" runat="server"/>
   7:   
   8:  <asp:GridView ID="gridviewExtractedFiles" runat="server" 
   9:                AutoGenerateColumns="False">
  10:  <Columns>
  11:  <asp:BoundField DataField="FileName" 
  12:                  HeaderText="File Name"/>
  13:  <asp:BoundField DataField="UncompressedSize" 
  14:                  HeaderText="Size"/>
  15:  <asp:BoundField DataField="CompressedSize"   
  16:                  HeaderText="Compressed Size">
  17:  </asp:BoundField>
  18:  </Columns>
  19:  </asp:GridView>

C# CODE
using System;
using System.IO;
using Ionic.Zip;
protected void btnExtract_Click(object sender, EventArgs e)
    {
        if (fileUpload1.HasFile)
        {
            string uploadedFile = Path.GetFileName(fileUpload1.PostedFile.FileName);
            string location = Server.MapPath("~/ZipFiles/" + uploadedFile);
            fileUpload1.SaveAs(location);
        
            ZipFile fileToExtract = ZipFile.Read(location);
            fileToExtract.ExtractAll(Server.MapPath("~/csharpdotnetfreak.blogspot.com"), ExtractExistingFileAction.DoNotOverwrite);
            gridviewExtracted.DataSource = fileToExtract.Entries;
            gridviewExtracted.DataBind();
            lblMessage.Text = "Archive extracted successfully and containes following files";
        }
   } 

We can use ExtractSelectedEntries method instead of ExtractAll to extract specific files such as *.jpg

VB.NET
Protected Sub btnExtract_Click(sender As Object, e As EventArgs)
 If fileUpload1.HasFile Then
  Dim uploadedFile As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
  Dim location As String = Server.MapPath("~/ZipFiles/" & uploadedFile)
  fileUpload1.SaveAs(location)

  Dim fileToExtract As ZipFile = ZipFile.Read(location)
  fileToExtract.ExtractAll(Server.MapPath("~/csharpdotnetfreak.blogspot.com"), ExtractExistingFileAction.DoNotOverwrite)
  gridviewExtracted.DataSource = fileToExtract.Entries
  gridviewExtracted.DataBind()
  lblMessage.Text = "Archive extracted successfully and containes following files"
 End If
End Sub
Build and run the application

Download Sample Code


2

Delete Files Directory Sub Directories From Server In Asp.Net

This example explains How To Delete Files Folders Directory And Sub Directories From Server In Asp.Net Using C# And VB.NET

I have placed one GridView on the aspx page to Display Directory or Contents of SubDirectory from server and have added one ButtonField In GridView Source for deletion when user clicks on button.

I have created one DataTable which is getting data with help of DirectoryInfo class.

I'm Deleting Files in RowCommand usingSystem.IO.File.Delete and Directories or folders using System.IO.Directory.Delete methods.

Delete Files Folders Directories From Server Directory In Asp.Net

HTML SOURCE OF GRIDVIEW
   1:  <asp:GridView ID="gridviewDeleteFiles" runat="server" 
   2:         onrowcommand="gridviewDeleteFiles_RowCommand" 
   3:         onrowdeleting="gridviewDeleteFiles_RowDeleting">
   4:  <Columns>
   5:  <asp:ButtonField Text="Delete" CommandName="Delete"/>
   6:  </Columns>
   7:  </asp:GridView>

C# CODE
using System.Data;
using System.IO;
protected void Page_Load(object sender, EventArgs e)
    {
       FillGridView();
    }
private void FillGridView()
    {
        DataTable dtGridViewSource = new DataTable();
        dtGridViewSource.Columns.Add(new DataColumn("Name", typeof(System.String)));
        dtGridViewSource.Columns.Add(new DataColumn("Size", typeof(System.String)));
        dtGridViewSource.Columns.Add(new DataColumn("Type", typeof(System.String)));
        dtGridViewSource.Columns.Add(new DataColumn("Path", typeof(System.String)));
        DataRow gridviewRow;

        //Get All Folders Or Directories and add in table
        DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/csharpdotnetfreak.blogspot.com"));
        DirectoryInfo[] subDirectories = directory.GetDirectories();
        foreach (DirectoryInfo dirInfo in subDirectories)
        {
            gridviewRow = dtGridViewSource.NewRow();
            gridviewRow["Name"] = dirInfo.Name;
            gridviewRow["Type"] = "Directory";
            gridviewRow["Path"] = dirInfo.FullName;
            dtGridViewSource.Rows.Add(gridviewRow);
        }
        //Get files in all directories 
        FileInfo[] files = directory.GetFiles("*.*", SearchOption.AllDirectories);
        foreach (FileInfo fileInfo in files)
        {
            gridviewRow = dtGridViewSource.NewRow();
            gridviewRow["Name"] = fileInfo.Name;
            gridviewRow["Size"] = fileInfo.Length;
            gridviewRow["Type"] = "File";
            gridviewRow["Path"] = fileInfo.FullName;
            dtGridViewSource.Rows.Add(gridviewRow);
         }
        gridviewDeleteFiles.DataSource = dtGridViewSource;
        gridviewDeleteFiles.DataBind();
    }

protected void gridviewDeleteFiles_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            GridViewRow row = gridviewDeleteFiles.Rows[Convert.ToInt32(e.CommandArgument)];
            string fileName = row.Cells[1].Text;
            string filePath = row.Cells[4].Text;
            string type = row.Cells[3].Text;
            if (type == "File")
            {
                System.IO.File.Delete(filePath);
            }
            else if (type == "Directory")
            {
                System.IO.Directory.Delete(filePath, true);

            }
        }
        FillGridView();
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 FillGridView()
End Sub

Private Sub FillGridView()
 Dim dtGridViewSource As New DataTable()
 dtGridViewSource.Columns.Add(New DataColumn("Name", GetType(System.String)))
 dtGridViewSource.Columns.Add(New DataColumn("Size", GetType(System.String)))
 dtGridViewSource.Columns.Add(New DataColumn("Type", GetType(System.String)))
 dtGridViewSource.Columns.Add(New DataColumn("Path", GetType(System.String)))
 Dim gridviewRow As DataRow

 'Get All Folders Or Directories and add in table
 Dim directory As New DirectoryInfo(Server.MapPath("~/csharpdotnetfreak.blogspot.com"))
 Dim subDirectories As DirectoryInfo() = directory.GetDirectories()
 For Each dirInfo As DirectoryInfo In subDirectories
  gridviewRow = dtGridViewSource.NewRow()
  gridviewRow("Name") = dirInfo.Name
  gridviewRow("Type") = "Directory"
  gridviewRow("Path") = dirInfo.FullName
  dtGridViewSource.Rows.Add(gridviewRow)
 Next
 'Get files in all directories 
 Dim files As FileInfo() = directory.GetFiles("*.*", SearchOption.AllDirectories)
 For Each fileInfo As FileInfo In files
  gridviewRow = dtGridViewSource.NewRow()
  gridviewRow("Name") = fileInfo.Name
  gridviewRow("Size") = fileInfo.Length
  gridviewRow("Type") = "File"
  gridviewRow("Path") = fileInfo.FullName
  dtGridViewSource.Rows.Add(gridviewRow)
 Next
 gridviewDeleteFiles.DataSource = dtGridViewSource
 gridviewDeleteFiles.DataBind()
End Sub

Protected Sub gridviewDeleteFiles_RowCommand(sender As Object, e As GridViewCommandEventArgs)
 If e.CommandName = "Delete" Then
  Dim row As GridViewRow = gridviewDeleteFiles.Rows(Convert.ToInt32(e.CommandArgument))
  Dim fileName As String = row.Cells(1).Text
  Dim filePath As String = row.Cells(4).Text
  Dim type As String = row.Cells(3).Text
  If type = "File" Then
   System.IO.File.Delete(filePath)
  ElseIf type = "Directory" Then

   System.IO.Directory.Delete(filePath, True)
  End If
 End If
 FillGridView()
End Sub

Download Sample Code


2

Display Files In GridView From Server Directory Asp.Net

This Example Show How To Display Files Directory Sub Directories In GridView From Server Folder In Asp.Net application using C# and Vb.Net.

We need to use DirectoryInfo class under System.IO namespace.

I'm displaying all files and directories (folders) from sever in gridview in page load.

I m creating a datatable in code behind with Name, Size and Type columns and assigning it as DataSource to Gridview.

Data in DataTable rows is coming from looping through all file and folder information stored in FileInfo or DirectoryInfo Arrays of GetFiles and GetDirectories methods of DirectoryInfo Class Object,

GetFiles method returns all the files and GetDirectories method returns all the directories or folder in server path specified.
Display Files Folders Directories In GridView From Server Folder Asp.Net

To search all files i'm passing *.* and SearchOption.AllDirectories parameters in GetDirectories method,

we can display specific file type in gridview by specifying it's extension instead of *.* (for example *.jpg or filename.*). SearchOption.AllDirectories parameter search files in all sub directories

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        DataTable gvSource = DisplayFilesInGridView();
        DataRow gvRow;

        //Get All Folders Or Directories and add in table
        DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/csharpdotnetfreak.blogspot.com"));
        DirectoryInfo[] subDirectories = directory.GetDirectories();
        foreach (DirectoryInfo dirInfo in subDirectories)
        {
            gvRow = gvSource.NewRow();
            gvRow["Name"] = dirInfo.Name;
            gvRow["Type"] = "Directory";
            gvSource.Rows.Add(gvRow);
        }
        //Get files in all directories 
        FileInfo[] files = directory.GetFiles("*.*", SearchOption.AllDirectories);
        foreach (FileInfo fileInfo in files)
        {
            gvRow = gvSource.NewRow();
            gvRow["Name"] = fileInfo.Name;
            gvRow["Size"] = fileInfo.Length;
            gvRow["Type"] = "File";
            gvSource.Rows.Add(gvRow);
 
        }
        gridviewDisplayFilesDirectories.DataSource = gvSource;
        gridviewDisplayFilesDirectories.DataBind();
    }

    private DataTable DisplayFilesInGridView()
    {
        DataTable dtGvSource = new DataTable();
        dtGvSource.Columns.Add(new DataColumn("Name", typeof(System.String)));
        dtGvSource.Columns.Add(new DataColumn("Size", typeof(System.String)));
        dtGvSource.Columns.Add(new DataColumn("Type", typeof(System.String)));
        return dtGvSource;
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim gvSource As DataTable = DisplayFilesInGridView()
 Dim gvRow As DataRow

 'Get All Folders Or Directories and add in table
 Dim directory As New DirectoryInfo(Server.MapPath("~/csharpdotnetfreak.blogspot.com"))
 Dim subDirectories As DirectoryInfo() = directory.GetDirectories()
 For Each dirInfo As DirectoryInfo In subDirectories
  gvRow = gvSource.NewRow()
  gvRow("Name") = dirInfo.Name
  gvRow("Type") = "Directory"
  gvSource.Rows.Add(gvRow)
 Next
 'Get files in all directories 
 Dim files As FileInfo() = directory.GetFiles("*.*", SearchOption.AllDirectories)
 For Each fileInfo As FileInfo In files
  gvRow = gvSource.NewRow()
  gvRow("Name") = fileInfo.Name
  gvRow("Size") = fileInfo.Length
  gvRow("Type") = "File"

  gvSource.Rows.Add(gvRow)
 Next
 gridviewDisplayFilesDirectories.DataSource = gvSource
 gridviewDisplayFilesDirectories.DataBind()
End Sub

Private Function DisplayFilesInGridView() As DataTable
 Dim dtGvSource As New DataTable()
 dtGvSource.Columns.Add(New DataColumn("Name", GetType(System.String)))
 dtGvSource.Columns.Add(New DataColumn("Size", GetType(System.String)))
 dtGvSource.Columns.Add(New DataColumn("Type", GetType(System.String)))
 Return dtGvSource
End Function


Download Sample Code


8

Forgot Password By Email Page Code In Asp.Net

This Example explains how to Create Forgot Password By Email Page Code In Asp.Net Using C# And VB.NET.

I have placed one textbox and button on the ForgotPassword.aspx page to send mail to email id stored in database.

You can also send Reset Password Link instead of sending Username password in the email.

Forgot Password By Email Page In Asp.Net


HTML SOURCE OF FORGOT PASSWORD PAGE
   1:  <form id="Form1" runat="server">
   2:  <div>
   3:  <fieldset>
   4:  <legend>Forgot Password</legend> 
   5:  <asp:Label ID="lblEmail" runat="server" Text="Email Address: "/>
   6:  <asp:TextBox ID="txtEmail" runat="server"/>
   7:   
   8:  <asp:RequiredFieldValidator ID="RV1" runat="server" 
   9:                              ControlToValidate="txtEmail" 
  10:                              ErrorMessage="Please Enter EmailID" 
  11:                              SetFocusOnError="True">*
  12:  </asp:RequiredFieldValidator>
  13:   
  14:  <asp:Button ID="btnPass" runat="server" Text="Submit" 
  15:                           onclick="btnPass_Click"/>
  16:   
  17:  <asp:ValidationSummary ID="ValidationSummary1" 
  18:                         runat="server" CssClass="error"/>
  19:                         
  20:  <asp:Label ID="lblMessage" runat="server" Text=""/>
  21:  </fieldset>
  22:  </div>
  23:  </form>


Write following code in Click Event of Button to retrieve username and password associated with EmailID provided by user from database and send the information to this email id.

C# CODE
using System;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Net.Mail;

protected void btnPass_Click(object sender, EventArgs e)
    {
        //Create Connection String And SQL Statement
        string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string strSelect = "SELECT UserName,Password FROM Users WHERE Email = @Email";

        SqlConnection connection = new SqlConnection(strConnection);
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
        command.CommandText = strSelect;

        SqlParameter email = new SqlParameter("@Email", SqlDbType.VarChar, 50);
        email.Value = txtEmail.Text.Trim().ToString();
        command.Parameters.Add(email);

        //Create Dataset to store results and DataAdapter to fill Dataset 
        DataSet dsPwd = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter(command);
        connection.Open();
        dAdapter.Fill(dsPwd);
        connection.Close();
        if(dsPwd.Tables[0].Rows.Count > 0 )
        {
            MailMessage loginInfo = new MailMessage();
            loginInfo.To.Add(txtEmail.Text.ToString());
            loginInfo.From = new MailAddress("YourID@gmail.com");
            loginInfo.Subject = "Forgot Password Information";

            loginInfo.Body = "Username: " + dsPwd.Tables[0].Rows[0]["UserName"] + "

Password: " + dsPwd.Tables[0].Rows[0]["Password"] + "

"; loginInfo.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.Credentials = new System.Net.NetworkCredential("YourGmailID@gmail.com", "YourGmailPassword"); smtp.Send(loginInfo); lblMessage.Text = "Password is sent to you email id,you can now Login"; } else { lblMessage.Text = "Email Address Not Registered"; } }

VB.NET
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Data
Imports System.Net.Mail

Protected Sub btnPass_Click(sender As Object, e As EventArgs)
  'Create Connection String And SQL Statement
  Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
  Dim strSelect As String = "SELECT UserName,Password FROM Users WHERE Email = @Email"

  Dim connection As New SqlConnection(strConnection)
  Dim command As New SqlCommand()
  command.Connection = connection
  command.CommandType = CommandType.Text
  command.CommandText = strSelect

  Dim email As New SqlParameter("@Email", SqlDbType.VarChar, 50)
  email.Value = txtEmail.Text.Trim().ToString()
  command.Parameters.Add(email)

  'Create Dataset to store results and DataAdapter to fill Dataset 
  Dim dsPwd As New DataSet()
  Dim dAdapter As New SqlDataAdapter(command)
  connection.Open()
  dAdapter.Fill(dsPwd)
  connection.Close()
  If dsPwd.Tables(0).Rows.Count > 0 Then
   Dim loginInfo As New MailMessage()
   loginInfo.[To].Add(txtEmail.Text.ToString())
   loginInfo.From = New MailAddress("YourID@gmail.com")
   loginInfo.Subject = "Forgot Password Information"

   loginInfo.Body = "Username: " & Convert.ToString(dsPwd.Tables(0).Rows(0)("UserName")) & "

Password: " & Convert.ToString(dsPwd.Tables(0).Rows(0)("Password")) & "

" loginInfo.IsBodyHtml = True Dim smtp As New SmtpClient() smtp.Host = "smtp.gmail.com" smtp.Port = 587 smtp.EnableSsl = True smtp.Credentials = New System.Net.NetworkCredential("YourGmailID@gmail.com", "YourGmailPassword") smtp.Send(loginInfo) lblMessage.Text = "Password is sent to you email id,you can now Login" Else lblMessage.Text = "Email Address Not Registered" End If End Sub


Download Sample Code


8

Create Login Page Form Example In Asp.Net

This example shows how to Create Login Page Form In Asp.Net Using C# And VB.NET.

Create Login Page Example In Asp.Net

To create Login Page Example, i have added a new form and placed 2 textbox and one button on it.

RequiredFieldValidators are associated to respective textboxes to ensure they are not blank.

TextMode property of password textbox is set so that it displays * instead of letters.

We can also Login Control with membership provider database to create login page.

I have used a table called users to check username and password, schema is shown below.

Login Form In Asp.Net

You can use User Registration Form In Sign Up hyperlink and Forgot Password Page to retrieve password by email.

HTML SOURCE OF PAGE
<form id="Form1" runat="server">
<fieldset>
<legend>Login</legend> 
<div class='container'>
<asp:Label ID="Name" runat="server" Text="UserName:" CssClass="lbl"/>
<br/>
<asp:TextBox ID="txtUserName" runat="server" Height="22px"/>
<asp:RequiredFieldValidator ID="RV1" runat="server" 
                            ControlToValidate="txtUserName" 
                            ErrorMessage="Please Enter User Name" 
                            SetFocusOnError="True">*
</asp:RequiredFieldValidator><br />
</div>
 
<div class='container'>
<asp:Label ID="lblPwd" runat="server" Text="Password:" CssClass="lbl"/>
<br/>
<asp:TextBox ID="txtPwd" runat="server" TextMode="Password" 
                         CssClass="pwd" Height="22px"/>
<asp:RequiredFieldValidator ID="RV2" runat="server" 
                            ControlToValidate="txtPwd" 
                            ErrorMessage="Your Password" 
                            SetFocusOnError="True">*
</asp:RequiredFieldValidator><br />
</div>
 
<div class='container'>
<asp:Button ID="btnLogIn" runat="server" Text="Sign In" 
                          onclick="btnLogIn_Click"/>
</div>
                       
<div class='container'>
<asp:HyperLink ID="HyperLink1" runat="server" 
NavigateUrl="~/ForgotPassword.aspx">Forgot Password ?</asp:HyperLink>
<br/>
</div>
<div class='short_explanation'>New User ? 
<asp:HyperLink ID="HyperLink2" runat="server" 
NavigateUrl="~/Default.aspx">SignUp !</asp:HyperLink></div>                       
<asp:ValidationSummary ID="ValidationSummary1" 
                       runat="server" CssClass="error"/>
<br /><br />
<asp:Label ID="lblMsg" runat="server" Text="" CssClass="lbl"/>
</fieldset>
</form>


Write following code in Click Event of Log In Button.

C#
protected void btnLogIn_Click(object sender, EventArgs e)
    {
        //Create Connection String And SQL Statement
        string strCon = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string strSelect = "SELECT COUNT(*) FROM Users WHERE UserName = @Username AND Password = @Password";

        SqlConnection con = new SqlConnection(strCon);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = strSelect;

        SqlParameter username = new SqlParameter("@Username", SqlDbType.VarChar, 50);
        username.Value = txtUserName.Text.Trim().ToString();
        cmd.Parameters.Add(username);

        SqlParameter password = new SqlParameter("@Password", SqlDbType.VarChar, 50);
        password.Value = txtPwd.Text.Trim().ToString();
        cmd.Parameters.Add(password);

        con.Open();
        int result = (Int32)cmd.ExecuteScalar();
        con.Close();

        if (result >= 1)
        {
            Response.Redirect("UpdateProfile.aspx");
        }
        else
            lblMsg.Text = "Incorrect Username or Password";
        
    }

VB.NET
Protected Sub btnLogIn_Click(sender As Object, e As EventArgs)
 'Create Connection String And SQL Statement
 Dim strCon As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
 Dim strSelect As String = "SELECT COUNT(*) FROM Users WHERE UserName = @Username AND Password = @Password"

 Dim con As New SqlConnection(strCon)
 Dim cmd As New SqlCommand()
 cmd.Connection = con
 cmd.CommandType = CommandType.Text
 cmd.CommandText = strSelect

 Dim username As New SqlParameter("@Username", SqlDbType.VarChar, 50)
 username.Value = txtUserName.Text.Trim().ToString()
 cmd.Parameters.Add(username)

 Dim password As New SqlParameter("@Password", SqlDbType.VarChar, 50)
 password.Value = txtPwd.Text.Trim().ToString()
 cmd.Parameters.Add(password)

 con.Open()
 Dim result As Integer = DirectCast(cmd.ExecuteScalar(), Int32)
 con.Close()

 If result >= 1 Then
  Response.Redirect("UpdateProfile.aspx")
 Else
  lblMsg.Text = "Incorrect Username or Password"
 End If

End Sub


We can further use Forms Authentication to anonymous access to site.

Download Sample Code


Find More Articles