0

Download File From Server In Asp.Net

Download files from server in asp.net
Download files from server or hyperlink in asp.net

In this post i'm explaining how to download a file from server in asp.net and display Save As dialog box when a link is clicked on the site.

For this example i have created a folder named Files on the server and stored Some sample files to download.

First we need to write code to display names of all the file saved in Files folder as hyperlinks so that user can download these files.


Write below mentioned code in Page_Load event of page where you want to display all the links with file names.



C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/Files"));
        int counter = 0;
        foreach (FileInfo file in directory.GetFiles())
        {
            HyperLink link = new HyperLink();
            link.ID = "Link" + counter++;
            link.Text = file.Name;
            link.NavigateUrl = "Default2.aspx?name="+file.Name;
            
            Page.Controls.Add(link);
            Page.Controls.Add(new LiteralControl("<br/>"));
        }
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim directory As New DirectoryInfo(Server.MapPath("~/Files"))
 Dim counter As Integer = 0
 For Each file As FileInfo In directory.GetFiles()
  Dim link As New HyperLink()
  link.ID = "Link" & System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
  link.Text = file.Name
  link.NavigateUrl = "Default2.aspx?name=" + file.Name

  Page.Controls.Add(link)
  Page.Controls.Add(New LiteralControl("<br/>"))
 Next
End Sub

Add a new web form Default2.aspx in the soulution and write code mentioned below in Page_Load Event.

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        string fileName = Request.QueryString["name"].ToString();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
        Response.TransmitFile(Server.MapPath("~/Files/" + fileName));
        Response.End();
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim fileName As String = Request.QueryString("name").ToString()
 Response.ContentType = "application/octet-stream"
 Response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)
 Response.TransmitFile(Server.MapPath("~/Files/" & fileName))
 Response.[End]()
End Sub

Build and run the code.

Download Sample Code



0

AspNet CompareValidator With Date Example

Asp.Net comparevalidator with dates example
Asp.Net CompareValidator Example to compare dates or textbox values

In this post i'm going to explain how to use CompareValidator to compare different values or dates.

For example We can use comparevalidator to compare values entered in password and confirm password textboxes which needs to be same, and using comparevalidator we don't need to wtite any code to check whether password in both textboxes are equal or not.

I have placed a textbox txtPwd for entering password and another textbox txtRePwd for re entering password.



To configure CompareValidator we need to assign ControlToCompare, ControlToValidate,Operator properties as mentioned below.

HTML SOURCE TO COMPARE PASSWORDS
   1:  <tr>
   2:  <td>Password:</td>
   3:  <td><asp:TextBox ID="txtPwd" runat="server"
   4:                   TextMode="Password">
   5:      </asp:TextBox>
   6:  </td>
   7:  </tr>
   8:  <tr>
   9:  <td>Confirm Password:</td>
  10:  <td><asp:TextBox ID="txtRePwd" runat="server"
  11:                   TextMode="Password">
  12:      </asp:TextBox>
  13:  </td>
  14:  <td>
  15:  <asp:CompareValidator ID="CompareValidator1" 
  16:       runat="server" 
  17:       ControlToCompare="txtRePwd" 
  18:       ControlToValidate="txtPwd" 
  19:       Operator="Equal" 
  20:       ErrorMessage="Password and confirm 
  21:                     password do not match" 
  22:       SetFocusOnError="True">
  23:  </asp:CompareValidator>
  24:  </td>
  25:  </tr>

We can also use comparevalidator to compare or validate dates.
For comparing date we need to define Type property of comparevalidator to Date.


HTML SOURCE TO COMPARE DATES
   1:  <asp:CompareValidator ID="CompareValidator2" 
   2:       runat="server"
   3:       ControlToCompare="txtLastDate"
   4:       ControlToValidate="txtRegDate" 
   5:       ErrorMessage="Please enter registration 
   6:                     date earlier then last date"
   7:       Operator="LessThanEqual" Type="Date" 
   8:       ValueToCompare="<%= txtLastDate.Text.ToShortString() %>">*
   9:  </asp:CompareValidator>

Hope this helps.


0

Create User Registration Form In AspNet

Creating user registration form in asp.net
Creating user registration form example in asp.net

In this post i am explaining how to create user registration or signup form in asp.net with sql server database using C# and VB.NET.

For this first of all we need to create a table in sql server database to store user registration data.

I have created a table named Users for this example with columns shown in image below.







Place textboxes on the form for entering name,username,password,address,email etc.

Set Textmode property of password textbox to password to display * character instead of text entered.

Associate RequiredFieldValidators with textboxes as shown in HTML source.

Place one Label and Button to save the data.


HTML SOURCE OF PAGE
   1:  <table>
   2:  <tr>
   3:  <td>First Name:</td>
   4:  <td><asp:TextBox ID="txtFirstName" runat="server">
   5:     </asp:TextBox>
   6:  </td>
   7:  <td><asp:RequiredFieldValidator ID="rfvFirstName" 
   8:              runat="server" 
   9:              ControlToValidate="txtFirstName"
  10:              ErrorMessage="First Name can't be left blank" 
  11:              SetFocusOnError="True">*
  12:       </asp:RequiredFieldValidator>
  13:  </td>
  14:  </tr>
  15:  <tr>
  16:  <td>Last Name:</td>
  17:  <td><asp:TextBox ID="txtLastName" runat="server">
  18:      </asp:TextBox></td>
  19:  <td><asp:RequiredFieldValidator 
  20:           ID="RequiredFieldValidator1" runat="server" 
  21:           ControlToValidate="txtLastName"
  22:           ErrorMessage="Last Name can't be left blank" 
  23:           SetFocusOnError="True">*
  24:      </asp:RequiredFieldValidator>
  25:  </td></tr>
  26:   
  27:  <tr><td>UserName:</td>
  28:  <td><asp:TextBox ID="txtUserName" runat="server">
  29:      </asp:TextBox>
  30:  </td>
  31:  <td><asp:RequiredFieldValidator 
  32:           ID="rfvUserName" 
  33:           runat="server" 
  34:           ControlToValidate="txtUserName"
  35:           ErrorMessage="UserName can't be left blank" 
  36:           SetFocusOnError="True">*
  37:      </asp:RequiredFieldValidator>
  38:  </td></tr>
  39:   
  40:  <tr><td>Password:</td>
  41:  <td><asp:TextBox ID="txtPwd" runat="server"
  42:                   TextMode="Password">
  43:      </asp:TextBox>
  44:  </td>
  45:  <td><asp:RequiredFieldValidator ID="rfvPwd" 
  46:           runat="server" ControlToValidate="txtPwd"
  47:           ErrorMessage="Password can't be left blank" 
  48:           SetFocusOnError="True">*
  49:     </asp:RequiredFieldValidator>
  50:  </td></tr>
  51:   
  52:  <tr><td>Confirm Password:</td>
  53:  <td><asp:TextBox ID="txtRePwd" runat="server"
  54:                   TextMode="Password">
  55:      </asp:TextBox>
  56:  </td>
  57:  <td><asp:CompareValidator ID="CompareValidator1" 
  58:           runat="server" 
  59:           ControlToCompare="txtRePwd" 
  60:           ControlToValidate="txtPwd" 
  61:           Operator="Equal" 
  62:           ErrorMessage="Password and confirm password do not match" 
  63:           SetFocusOnError="True">
  64:      </asp:CompareValidator>
  65:  </td></tr>
  66:   
  67:  <tr><td>Gender:</td>
  68:  <td><asp:RadioButtonList ID="rdoGender" 
  69:                           runat="server">
  70:           <asp:ListItem>Male</asp:ListItem>
  71:           <asp:ListItem>Female</asp:ListItem>
  72:      </asp:RadioButtonList>
  73:  </td>
  74:  <td><asp:RequiredFieldValidator 
  75:           ID="RequiredFieldValidator2" 
  76:           runat="server" 
  77:           ControlToValidate="rdoGender"
  78:           ErrorMessage="Gender can't be left blank" 
  79:           SetFocusOnError="True">*
  80:       </asp:RequiredFieldValidator>
  81:  </td></tr>
  82:   
  83:  <tr><td>Address:</td>
  84:  <td><asp:TextBox ID="txtAdress" runat="server" 
  85:                   TextMode="MultiLine">
  86:      </asp:TextBox>
  87:  </td>
  88:  <td><asp:RequiredFieldValidator ID="rfvAddress" 
  89:           runat="server" 
  90:           ControlToValidate="txtAdress"
  91:           ErrorMessage="Address can't be left blank" 
  92:           SetFocusOnError="True">*
  93:      </asp:RequiredFieldValidator>
  94:  </td></tr>
  95:                          
  96:  <tr><td>Email ID:</td>
  97:  <td><asp:TextBox ID="txtEmailID" runat="server">
  98:      </asp:TextBox>
  99:  </td>
 100:  <td><asp:RequiredFieldValidator 
 101:           ID="RequiredFieldValidator3" 
 102:           runat="server" 
 103:           ControlToValidate="txtEmailID"
 104:           ErrorMessage="Email can't be left blank" 
 105:           SetFocusOnError="True">*
 106:      </asp:RequiredFieldValidator>
 107:  </td></tr>
 108:   
 109:  <tr><td><asp:Label ID="lblMsg" runat="server">
 110:          </asp:Label>
 111:      </td>
 112:  <td><asp:ValidationSummary ID="ValidationSummary1" 
 113:           runat="server" ShowMessageBox="True" 
 114:           ShowSummary="False"/>
 115:  </td></tr>
 116:   
 117:  <tr><td><asp:Button ID="btnSave" runat="server" 
 118:                      Text="Sign Up" 
 119:                      onclick="btnSave_Click"/>
 120:  </td></tr>
 121:  </table>

Write below mentioned code in click event of signup button.

C# CODE
protected void btnSave_Click(object sender, EventArgs e)
    {
        //Create ConnectionString and Inser Statement
        string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string insertSql = "INSERT INTO Users (FirstName,LastName,UserName,Password,Email,Address,Gender)" 
        + " values (@FirstName,@LastName,@UserName,@Password,@Email,@Address,@Gender)";
        //Create SQL connection
        SqlConnection con = new SqlConnection(connectionString);
        
        //Create SQL Command And Sql Parameters

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = insertSql;

        SqlParameter firstName = new SqlParameter("@FirstName", SqlDbType.VarChar, 50);
        firstName.Value = txtFirstName.Text.ToString();
        cmd.Parameters.Add(firstName);

        SqlParameter lastName = new SqlParameter("@LastName", SqlDbType.VarChar, 50);
        lastName.Value = txtLastName.Text.ToString();
        cmd.Parameters.Add(lastName);

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

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

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

        SqlParameter address = new SqlParameter("@Address", SqlDbType.VarChar, 50);
        address.Value = txtAdress.Text.ToString();
        cmd.Parameters.Add(address);

        SqlParameter gender = new SqlParameter("@Gender", SqlDbType.VarChar, 10);
        gender.Value = rdoGender.SelectedItem.ToString();
        cmd.Parameters.Add(gender);

        
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            lblMsg.Text = "User Registration successful";
        }
        catch (SqlException ex)
        {
            string errorMessage = "Error in registring user";
            errorMessage += ex.Message;
            throw new Exception(errorMessage);

        }
        finally
        {
            con.Close();
        }
    }

VB.NET CODE
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
 'Create ConnectionString and Inser Statement
 Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
 Dim insertSql As String = "INSERT INTO Users (FirstName,LastName,UserName,Password,Email,Address,Gender)" & " values (@FirstName,@LastName,@UserName,@Password,@Email,@Address,@Gender)"
 'Create SQL connection
 Dim con As New SqlConnection(connectionString)

 'Create SQL Command And Sql Parameters

 Dim cmd As New SqlCommand()
 cmd.Connection = con
 cmd.CommandType = CommandType.Text
 cmd.CommandText = insertSql

 Dim firstName As New SqlParameter("@FirstName", SqlDbType.VarChar, 50)
 firstName.Value = txtFirstName.Text.ToString()
 cmd.Parameters.Add(firstName)

 Dim lastName As New SqlParameter("@LastName", SqlDbType.VarChar, 50)
 lastName.Value = txtLastName.Text.ToString()
 cmd.Parameters.Add(lastName)

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

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

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

 Dim address As New SqlParameter("@Address", SqlDbType.VarChar, 50)
 address.Value = txtAdress.Text.ToString()
 cmd.Parameters.Add(address)

 Dim gender As New SqlParameter("@Gender", SqlDbType.VarChar, 10)
 gender.Value = rdoGender.SelectedItem.ToString()
 cmd.Parameters.Add(gender)


 Try
  con.Open()
  cmd.ExecuteNonQuery()
  lblMsg.Text = "User Registration successful"
 Catch ex As SqlException
  Dim errorMessage As String = "Error in registring user"
  errorMessage += ex.Message

  Throw New Exception(errorMessage)
 Finally
  con.Close()
 End Try
End Sub

Build and run the code.


Download Sample Code




1

Visual Studio Remove Unused References With Organize Usings

Visual studio Remove unused references using organize using
Remove unused references in visual studio by organize usings command

When we create a new website or project in visual studio, several namespace references are added in code behind by default.

It's always advisable to remove all unused usings and references from code behind for better performance.

We can follow steps mentioned below to remove all unused usings and references.

FOR C# APPLICATIONS OR PROJECTS

Open code behind of the page u want to remove unused references,
Right click > Organize Usings > Remove Unused Usings




All unused usings will be removed as shown below.



FOR VB.NET APPLICATIONS AND PROJECTS

Right click on My Project in solution explorer > Select Open.


Select References tab and click on unused references button.


Check the check box for references you want to remove and click on remove.


Hope this helps.


1

Get RowIndex In GridView RowCommand Event Using DataKey CommandArgument

Get RowIndex In GridView RowCommand Event Using DataKey or CommandArgument in asp.net

In this post i am showing how to get RowIndex of gridview row in RowCommand Event through DataKey property or commandArgument.

RowCommand event is raised when a button inside gridview is clicked.

Method 1.

To get gridview rowindex through DataKey property we can use code as mentioned below.

For this we need to define DataKeyNames property in gridview.



HTML SOURCE
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1" 
              onrowcommand="GridView1_RowCommand" 
              DataKeyNames="DocID">
<Columns>
<asp:BoundField DataField="DocID" HeaderText="DocID" 
                InsertVisible="False" 
                ReadOnly="True" 
                SortExpression="DocID" />

<asp:ButtonField ButtonType="Button"  
                CommandName="Show" 
                Text="Show"/>
                
</Columns>
</asp:GridView>

Write this code in RowCommand Event of gridview to get rowindex or row number in which button was clicked.

C# CODE
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Show")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            int documentID = Convert.ToInt32(GridView1.DataKeys[index].Value);
           
             // Write your further code
            
        }
    }

VB.NET CODE
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
 If e.CommandName = "Show" Then
  Dim index As Integer = Convert.ToInt32(e.CommandArgument)
  Dim documentID As Integer = Convert.ToInt32(GridView1.DataKeys(index).Value)
                 
                ' Write your further code
 End If
End Sub


Method 2.

To get rowindex without using DataKey we can write code as mentioned below.

C# CODE
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Show")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = GridView1.Rows[index];
            int docID = Convert.ToInt32(row.Cells[0].Text);
           
            // Write your further code here 
        }
     }

VB.NET CODE
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
 If e.CommandName = "Show" Then
  Dim index As Integer = Convert.ToInt32(e.CommandArgument)
  Dim row As GridViewRow = GridView1.Rows(index)
  Dim docID As Integer = Convert.ToInt32(row.Cells(0).Text)

               ' Write your further code here 
 End If
End Sub

If we have placed controls like label,textbox or dropdowns in the gridview row then we can access these controls in following manner.

HTML SOURCE
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1" 
              onrowcommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="DocID" HeaderText="DocID" 
                InsertVisible="False" 
                ReadOnly="True" 
                SortExpression="DocID" />

<asp:ButtonField ButtonType="Button"  
                CommandName="Show" 
                Text="Show"/>
                
<asp:TemplateField HeaderText="Message">
<ItemTemplate>
<asp:Label ID="lblMessage" runat="server" 
           Text='<%#Eval("DocName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

C# CODE
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Show")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = GridView1.Rows[index];
            int docID = Convert.ToInt32(row.Cells[0].Text);
            string labelText = ((Label)row.FindControl("lblMessage")).Text.ToString();
        }
    }

If we want to place a button inside TemplateField then we need to define CommandArgument property manually in html source as follows.

<asp:TemplateField>
 <ItemTemplate>                
 <asp:Button runat="server" ID="btnDn"
             Text="Down" CommandName="Show" 
CommandArgument="<%#((GridViewRow)Container).RowIndex%>"/>
</ItemTemplate>
</asp:TemplateField>

Hope this helps


0

Save Store Files In SqlServer Database AspNet

Save or Store files in sqlserver database asp.net
Upload and Save Or Store Files In Ms Sql Server Database using fileupload control in Asp.Net.

In this post i'm explaining how to save or store and retrieve pdf,word,excel,jpeg,gif,png files in MS sqlserver database using fileupload in asp.net.

I'll also explain how to retrieve files from sql database for users to download.

For this example i have created a sample database with table name SaveDoc to save documents in it. table schema is shown below in image.

Read Display Images In GridView From SqlServer DataBase Asp.Net to know how to save and retrieve images in sql database and display them in gridview using handler.




For uploading and saving files to database we need to use Fileupload control, so drag and place one fileupload control and one button on the aspx page in design mode.

Place one label on the page to display success or failure message, and one gridview to display uploaded documents and provide link to download document files.

I have added one button field in gridview to provide download link to file shown in respective row of gridview and this gridview is populated by sqlDataSource.

HTML SOURCE OF THE PAGE
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="btnUpload" runat="server"  
            onclick="btnUpload_Click" 
            Text="Upload"/>
</div>
<br/>
<asp:Label ID="lblMessage" runat="server">
</asp:Label><br /><br /><br />
      
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1" 
              onrowcommand="GridView1_RowCommand" 
              DataKeyNames="DocID">
<Columns>
<asp:BoundField DataField="DocID" HeaderText="DocID" 
                InsertVisible="False" 
                ReadOnly="True" 
                SortExpression="DocID" />

<asp:BoundField DataField="DocName" 
                HeaderText="DocName" 
                SortExpression="DocName" />

<asp:BoundField DataField="Type" HeaderText="Type" 
                SortExpression="Type" />
            
<asp:ButtonField ButtonType="Image"  
                ImageUrl="~/download.png" 
                CommandName="Download" 
                HeaderText="Download" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
SelectCommand="SELECT [DocID], [DocName], [Type] 
               FROM [SaveDoc]">
</asp:SqlDataSource>
</form>

To upload and save files in database write code mentioned below in Click event of upload button we placed on aspx page.

C# CODE
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Check whether FileUpload control has file 
        if (FileUpload1.HasFile)
        {
            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
            string documentType = string.Empty;

            //provide document type based on it's extension
            switch (fileExtension)
            {
                case ".pdf":
                    documentType = "application/pdf";
                    break;
                case ".xls":
                    documentType = "application/vnd.ms-excel";
                    break;
                case ".xlsx":
                    documentType = "application/vnd.ms-excel";
                    break;
                case ".doc":
                    documentType = "application/vnd.ms-word";
                    break;
                case ".docx":
                    documentType = "application/vnd.ms-word";
                    break;
                case ".gif":
                    documentType = "image/gif";
                    break;
                case ".png":
                    documentType = "image/png";
                    break;
                case ".jpg":
                    documentType = "image/jpg";
                    break;
            }

            //Calculate size of file to be uploaded
            int fileSize = FileUpload1.PostedFile.ContentLength;

            //Create array and read the file into it
            byte[] documentBinary = new byte[fileSize];
            FileUpload1.PostedFile.InputStream.Read(documentBinary, 0, fileSize);

            // Create SQL Connection 
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            // Create SQL Command and Sql Parameters 
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO SaveDoc(DocName,Type,DocData)" +
                              " VALUES (@DocName,@Type,@DocData)";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;

            SqlParameter DocName = new SqlParameter("@DocName", SqlDbType.VarChar, 50);
            DocName.Value = fileName.ToString();
            cmd.Parameters.Add(DocName);

            SqlParameter Type = new SqlParameter("@Type", SqlDbType.VarChar, 50);
            Type.Value = documentType.ToString();
            cmd.Parameters.Add(Type);

            SqlParameter uploadedDocument = new SqlParameter("@DocData", SqlDbType.Binary,fileSize);
            uploadedDocument.Value = documentBinary;
            cmd.Parameters.Add(uploadedDocument);

            con.Open();
            int result = cmd.ExecuteNonQuery();
            con.Close();
            if (result > 0)
                lblMessage.Text = "File saved to database";
            GridView1.DataBind();
        }
    }

VB.NET CODE
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
 'Check whether FileUpload control has file 
 If FileUpload1.HasFile Then
  Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
  Dim fileExtension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
  Dim documentType As String = String.Empty

  'provide document type based on it's extension
  Select Case fileExtension
   Case ".pdf"
    documentType = "application/pdf"
    Exit Select
   Case ".xls"
    documentType = "application/vnd.ms-excel"
    Exit Select
   Case ".xlsx"
    documentType = "application/vnd.ms-excel"
    Exit Select
   Case ".doc"
    documentType = "application/vnd.ms-word"
    Exit Select
   Case ".docx"
    documentType = "application/vnd.ms-word"
    Exit Select
   Case ".gif"
    documentType = "image/gif"
    Exit Select
   Case ".png"
    documentType = "image/png"
    Exit Select
   Case ".jpg"
    documentType = "image/jpg"
    Exit Select
  End Select

  'Calculate size of file to be uploaded
  Dim fileSize As Integer = FileUpload1.PostedFile.ContentLength

  'Create array and read the file into it
  Dim documentBinary As Byte() = New Byte(fileSize - 1) {}
  FileUpload1.PostedFile.InputStream.Read(documentBinary, 0, fileSize)

  ' Create SQL Connection 
  Dim con As New SqlConnection()
  con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString

  ' Create SQL Command and Sql Parameters 
  Dim cmd As New SqlCommand()
  cmd.CommandText = "INSERT INTO SaveDoc(DocName,Type,DocData)" & " VALUES (@DocName,@Type,@DocData)"
  cmd.CommandType = CommandType.Text
  cmd.Connection = con

  Dim DocName As New SqlParameter("@DocName", SqlDbType.VarChar, 50)
  DocName.Value = fileName.ToString()
  cmd.Parameters.Add(DocName)

  Dim Type As New SqlParameter("@Type", SqlDbType.VarChar, 50)
  Type.Value = documentType.ToString()
  cmd.Parameters.Add(Type)

  Dim uploadedDocument As New SqlParameter("@DocData", SqlDbType.Binary, fileSize)
  uploadedDocument.Value = documentBinary
  cmd.Parameters.Add(uploadedDocument)

  con.Open()
  Dim result As Integer = cmd.ExecuteNonQuery()
  con.Close()
  If result > 0 Then
   lblMessage.Text = "File saved to database"
  End If
  GridView1.DataBind()
 End If
End Sub


To retrieve files from database for download in click of download button we put in gridview, we need to write code mentioned below in RowCommand Event of gridview

c# CODE
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        {
            string fileName = string.Empty;
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = GridView1.Rows[index];
            int documentID = Convert.ToInt32(GridView1.DataKeys[index].Value);
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand("SELECT DocName,DocData FROM SaveDoc WHERE DocID = " + documentID, con);
            con.Open();
            SqlDataReader dReader = cmd.ExecuteReader();
            while (dReader.Read())
            {
                fileName = dReader["DocName"].ToString();
                byte[] documentBinary = (byte[])dReader["DocData"];
                FileStream fStream = new FileStream(Server.MapPath("Docs") + @"\" + fileName, FileMode.Create);
                fStream.Write(documentBinary, 0, documentBinary.Length);
                fStream.Close();
                fStream.Dispose();
            }
            con.Close();
            Response.Redirect(@"Docs\" + fileName);
        }
    }

VB.NET CODE
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
 If e.CommandName = "Download" Then
  Dim fileName As String = String.Empty
  Dim index As Integer = Convert.ToInt32(e.CommandArgument)
  Dim row As GridViewRow = GridView1.Rows(index)
  Dim documentID As Integer = Convert.ToInt32(GridView1.DataKeys(index).Value)
  Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
  Dim cmd As New SqlCommand("SELECT DocName,DocData FROM SaveDoc WHERE DocID = " & documentID, con)
  con.Open()
  Dim dReader As SqlDataReader = cmd.ExecuteReader()
  While dReader.Read()
   fileName = dReader("DocName").ToString()
   Dim documentBinary As Byte() = DirectCast(dReader("DocData"), Byte())
   Dim fStream As New FileStream(Server.MapPath("Docs") & "\" & fileName, FileMode.Create)
   fStream.Write(documentBinary, 0, documentBinary.Length)
   fStream.Close()
   fStream.Dispose()
  End While
  con.Close()
  Response.Redirect("Docs\" & fileName)
 End If
End Sub

Build and run the application.


Download Sample Code



2

Nested GridView In Asp.Net Or GridView Inside GridView(Master Detail)

Nested Gridview inside gridview in asp.net
Gridview inside gridview or nested gridview in Master Detail or Parent Child scenario in asp.net

In this post i am explaining how to create gridview inside gridview or nested gridview to show master detail or Parent Child data in asp.net.

For this i have used northwind database and customers and Orders table to display data.

Drag SqlDataSource1 on page and configure it to fetch data Customers table and select CustomerID and CustomerName fields in select statement.

Drag and drop sqlDataSource2 on the page and configure it to fetch data from Orders table based on customer id in where clause.



Place one gridview on the page and set SqlDataSource1 as it's datasource.

Create one TemplateField field in this gridview and put another gridview inside ItemTemplate and provide SqlDataSOurce2 as it's datasource, set it's visible property to False.

Complete HTML source of page will look like shown below.

HTML SOURCE OF THE PAGE
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" 
              AllowPaging="True" 
              AutoGenerateColumns="False" 
              DataKeyNames="CustomerID" 
              DataSourceID="SqlDataSource1" 
onselectedindexchanged="GridView1_SelectedIndexChanged">
<RowStyle VerticalAlign="Top" />
<Columns>
<asp:BoundField DataField="CustomerID" 
                HeaderText="CustomerID" 
                ReadOnly="True" 
                SortExpression="CustomerID" />

<asp:BoundField DataField="CompanyName" 
                HeaderText="CompanyName" 
                SortExpression="CompanyName" />
                
<asp:CommandField ShowSelectButton="True" 
                  SelectText="Show Details"/>
               
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="GridView2" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="OrderID" 
              DataSourceID="SqlDataSource2" 
              Visible="false">
<Columns>
<asp:BoundField DataField="OrderID" 
                HeaderText="OrderID" 
                InsertVisible="False" 
                ReadOnly="True" 
                SortExpression="OrderID" />
<asp:BoundField DataField="OrderDate" 
                HeaderText="OrderDate" 
                SortExpression="OrderDate" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" 
                   runat="server" 
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" 
SelectCommand="SELECT [CustomerID], [CompanyName] 
               FROM [Customers]">
</asp:SqlDataSource>

<asp:SqlDataSource ID="SqlDataSource2" 
                   runat="server" 
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" 
SelectCommand="SELECT [OrderID], [OrderDate] 
               FROM [Orders] 
               WHERE ([CustomerID] = @CustomerID)">
<SelectParameters>
<asp:Parameter Name="CustomerID" Type="String"/>
</SelectParameters>
</asp:SqlDataSource>
</div>
</form>

Now generate SelectedIndexChanged event for parent gridview (GridView1) and write code mentioned below.

C# CODE BEHIND

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        foreach (GridViewRow gvRow in GridView1.Rows)
        {
            gvRow.FindControl("GridView2").Visible = false;
        }
        SqlDataSource2.SelectParameters[0].DefaultValue = GridView1.SelectedDataKey[0].ToString();
        GridView1.SelectedRow.FindControl("GridView2").Visible = true;
    }


VB.NET CODE BEHIND

Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs)
 For Each gvRow As GridViewRow In GridView1.Rows
  gvRow.FindControl("GridView2").Visible = False
 Next
 SqlDataSource2.SelectParameters(0).DefaultValue = GridView1.SelectedDataKey(0).ToString()
 GridView1.SelectedRow.FindControl("GridView2").Visible = True
End Sub

Build and run the application.



0

Add License Agreement In Visual Studio Setup Project

Add License agreement in setup project
Add License Agreement In Setup Project using Visual Studio

In this post i am explaining steps to add license agreement dialog in visual studio setup project.

Read Create Setup And Deployment Project in Visual Studio 2008/2010 to know how to create setup for your winforms or asp.net applications.









step 1.

First of all we need to create a licence agreement file, for this open wordpad and type your licence agreement text and save it as licence.rtf.

Add this file in your project in solution explorer by select add existing item menu.


Step 2.

Right click on your setup project and select View > File System.

license agreement in visual studio setupproject

Step 3.

Right click on Application folder and select Add > File.

Browse to licence.rtf we added to solution in step 1.

Add license.rtf file

Step 4.

Right click on setup project in solution explorer and select View > User Interface.

UserInterface in setupproject

Step 5.

Right click on Start and select Add Dialog.

Add dialog in setup project

Select Licence agreement and click on OK.

License agreement dialog in setup project

Move it Up by right clicking and selecting Move Up to put it on the top to show up when setup starts.

Step 6.

Select Licence Agreement dialog in start group and open it's property window by pressing F4 key.



Click on Browse in LicenceFile property and select licence.rtf file from Application Folder and click on OK.

add licence.rtf to license agreement dialog

Save and build the setup project and licence agreement dialog will launch when you run setup.exe (as shown below).




Popular Posts

Find More Articles