Answered by:
select multiple checked items in gridview

Question
-
User-1767698477 posted
Based on an Article I read by Scott Mitchell, I have added some code to my page. The checkboxes are working and I can get the row so it should just be a matter of getting the docIDs of all the selected checkboxes into an array, and then all the files can be accessed to be put into a zip file.I'm not sure how to implement this. Will Asp.net take a list of files and stuff them into a file, and zip it up with password protection?
<%@ Page Title="" Language="VB" MasterPageFile="~/templates/default1.master" AutoEventWireup="false"
CodeFile="documents.aspx.vb" Inherits="users_documents" %><asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<title>Borrower Documents</title>
<script type="text/javascript">
function ChangeCheckBoxState(id, checkState) {
var cb = document.getElementById(id);
if (cb != null)
cb.checked = checkState;
}function ChangeAllCheckBoxStates(checkState) {
// Toggles through all of the checkboxes defined in the CheckBoxIDs array
// and updates their value to the checkState input parameter
if (CheckBoxIDs != null) {
for (var i = 0; i < CheckBoxIDs.length; i++)
ChangeCheckBoxState(CheckBoxIDs[i], checkState);
}
}function ChangeHeaderAsNeeded() {
// Whenever a checkbox in the GridView is toggled, we need to
// check the Header checkbox if ALL of the GridView checkboxes are
// checked, and uncheck it otherwise
if (CheckBoxIDs != null) {
// check to see if all other checkboxes are checked
for (var i = 1; i < CheckBoxIDs.length; i++) {
var cb = document.getElementById(CheckBoxIDs[i]);
if (!cb.checked) {
// Whoops, there is an unchecked checkbox, make sure
// that the header checkbox is unchecked
ChangeCheckBoxState(CheckBoxIDs[0], false);
return;
}
}// If we reach here, ALL GridView checkboxes are checked
ChangeCheckBoxState(CheckBoxIDs[0], true);
}
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div id="menu" class="container">
</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">
<form id="Form1" runat="server">
<table align="center" width="95%">
<tr>
<td align="left">
Welcome : <b>
<asp:Label ID="lblName" runat="server" Text="" ForeColor="#FFB30F"></asp:Label></b>
</td>
<td align="center">
</td>
<td align="right">
<asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="changepassword.aspx">Change Password</asp:HyperLink>
</td>
</tr>
<tr>
<td align="left">
<asp:LoginView ID="LoginView1" runat="server">
<LoggedInTemplate>
Logged in as :
<asp:LoginName ID="LoginName1" runat="server" Font-Bold="True" />
</LoggedInTemplate>
<AnonymousTemplate>
Your are not logged in.
<br />
Click the login link to sign in.
</AnonymousTemplate>
</asp:LoginView>
</td>
<td align="center">
</td>
<td align="right">
<asp:HyperLink ID="HyperLink4" runat="server" NavigateUrl="edit_profile.aspx">Edit Profile</asp:HyperLink>
</td>
</tr>
<tr>
<td align="left">
<asp:LoginStatus ID="LoginStatus1" runat="server" />
<a href="Default.aspx">Return</a>
</td>
<td align="center">
<br />
<h2>
Documents</h2>
<br />
</td>
<td align="right">
<asp:Button ID="NewApp" Text="Start New Application" runat="server" OnCommand="ClearSessionCommand"
CommandName="ClearSession"></asp:Button>
</td>
</tr>
</table>
<center>
<table align="center">
<tr>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
<td>
<asp:DropDownList ID="DDLdocuments" runat="server">
<asp:ListItem>Select Document Type</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
<br />
<center>
<asp:Button ID="Button1" runat="server" Text="Upload Document" />
</center>
<br />
<asp:Label ID="Label1" runat="server" Text="" ForeColor="#0033CC" Font-Bold="True"></asp:Label>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="" ForeColor="Black" Font-Bold="True"></asp:Label>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="DocID" DataSourceID="SqlDataSource1" ForeColor="Black"
GridLines="Vertical" BackColor="White" BorderColor="#999999" BorderStyle="Solid"
BorderWidth="1px" AllowPaging="True" CellSpacing="7">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server" ID="HeaderLevelCheckBox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="RowLevelCheckBox" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="Document Type" SortExpression="Doctype">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Doctype") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DDLdocuments2" runat="server" SelectedValue='<%# Bind("Doctype") %>'>
<asp:ListItem>Bank Statements (All pages)</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Docsize" HeaderText="Doc Size" ReadOnly="True" SortExpression="Docsize" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField DataField="Dat1eUploaded" HeaderText="Date Uploaded" ReadOnly="True"
SortExpression="DateUploaded" ItemStyle-HorizontalAlign="Right" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
<br />
<span onmouseout="UnTip()" onmouseover="Tip('To create a zip file for your processor, select files to zip by checking the boxes on the right. When you are done, click the button and your processor will be sent an email with a password protected zip file attached. Do not select more than 5MB of files as this can often be a problem for some email boxes.', WIDTH, 220, BGCOLOR, '#eeeeee')">
<img alt="" src="../templates/images/help.gif" />
</span>
<asp:Button ID="ZipandEmail" runat="server" Text="Create zip file & notify processor" />
</center>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:sqlConnectionString %>"
DeleteCommand="DELETE FROM [Documents] WHERE [DocID] = @DocID" InsertCommand="INSERT INTO [Documents] ([UserID], [ApplicantID], [Doctype], [DocFileName], [Docsize], [DateUploaded]) VALUES (@UserID, @ApplicantID, @Doctype, @DocFileName, @Docsize, @DateUploaded)"
SelectCommand="SELECT * FROM [Documents] WHERE ([ApplicantID] = @ApplicantID) ORDER BY [DateUploaded] DESC, [Doctype]"
UpdateCommand="UPDATE [Documents] SET [Doctype] = @Doctype WHERE [DocID] = @DocID">
<SelectParameters>
<asp:SessionParameter Name="ApplicantID" SessionField="ApplicantID" Type="String" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="DocID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="Doctype" Type="String" />
<asp:Parameter Name="DocID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="UserID" Type="Int32" />
<asp:Parameter Name="Doctype" Type="String" />
<asp:Parameter Name="DocFileName" Type="String" />
<asp:Parameter Name="Docsize" Type="String" />
<asp:Parameter Name="DateUploaded" Type="DateTime" />
</InsertParameters>
</asp:SqlDataSource>
<br />
<asp:Literal ID="CheckBoxIDsArray" runat="server"></asp:Literal>
<asp:Label ID="Summary" runat="server" EnableViewState="False" Font-Bold="False"
Font-Italic="False" Font-Size="XX-Large" ForeColor="Red"></asp:Label>
</form>
</asp:Content>Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Imports System.Web.Security
Imports DataSet1TableAdapters
Partial Class users_documents
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
If Session("username") = Nothing Then
lblName.Text = "You have been logged out due to inactivity - Please login again."
Exit Sub
End If
lblName.Text = Session("Firstname") & " " & Session("Lastname")
Label2.Text = "Uploaded Documents for " & Session("BorFirst") + " " + Session("BorLast")
Label1.Text = ""
End If
If FileUpload1.FileName = "" Then
Exit Sub
End If
End Sub
Protected Sub ViewCommand(sender As Object, e As CommandEventArgs)
Dim file As String = e.CommandArgument.ToString
Response.Redirect("/users/" & Session("path") & "/" & Session("docpath") + file)
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If DDLdocuments.SelectedValue = "Select Document Type" Then
Label1.Text = "You must select a document type"
Label1.Visible = True
Exit Sub
End If
If FileUpload1.HasFile Then
'Uncomment this line to Save the uploaded file
Dim path As String = Session("path") + "/" + Session("docpath") + "/"
'test for pdf and jpg files only
If Microsoft.VisualBasic.Right(FileUpload1.FileName, 4) <> ".pdf" Then
If Microsoft.VisualBasic.Right(FileUpload1.FileName, 4) <> ".jpg" Then
Label1.Text = "You can only upload .pdf or .jpg files"
Label1.Visible = True
Exit Sub
End If
End IfDim filesize As Double = FileUpload1.FileBytes.Length
If filesize > 5242880 Then
Label1.Text = "Only files up to 5MB may be uploaded"
Label1.Visible = True
Exit Sub
End If
Dim sizes As String() = {"B", "KB", "MB"}
Dim sizeinbytes As Double = fileUpload1.FileBytes.Length
Dim order As Integer = 0While sizeinbytes >= 1024 AndAlso order + 1 < sizes.Length
order += 1
sizeinbytes = sizeinbytes / 1024
End WhileDim result As String = String.Format("{0:0.##} {1}", sizeinbytes, sizes(order))
FileUpload1.SaveAs("C:\mortgageloanapply\users\" & path & FileUpload1.FileName)
Label1.Text = "Received " & FileUpload1.FileName & "<br>Content Type " & FileUpload1.PostedFile.ContentType & " Length " & FileUpload1.PostedFile.ContentLength & " please wait.."
LogFileUpload(Session("UserID"), Session("ApplicantID"), DDLdocuments.SelectedValue, FileUpload1.FileName, result)
GridView1.DataBind()
Else
Label1.Text = "No uploaded file"
End If
Response.AddHeader("REFRESH", "4;URL=documents.aspx")
End Sub
Protected Sub Gridview1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.DataBound
'Each time the data is bound to the grid we need to build up the CheckBoxIDs array'Get the header CheckBox
Dim cbHeader As CheckBox = CType(GridView1.HeaderRow.FindControl("HeaderLevelCheckBox"), CheckBox)'Run the ChangeCheckBoxState client-side function whenever the
'header checkbox is checked/unchecked
cbHeader.Attributes("onclick") = "ChangeAllCheckBoxStates(this.checked);"'Add the CheckBox's ID to the client-side CheckBoxIDs array
Dim ArrayValues As New List(Of String)
ArrayValues.Add(String.Concat("'", cbHeader.ClientID, "'"))For Each gvr As GridViewRow In GridView1.Rows
'Get a programmatic reference to the CheckBox control
Dim cb As CheckBox = CType(gvr.FindControl("RowLevelCheckBox"), CheckBox)'If the checkbox is unchecked, ensure that the Header CheckBox is unchecked
cb.Attributes("onclick") = "ChangeHeaderAsNeeded();"'Add the CheckBox's ID to the client-side CheckBoxIDs array
ArrayValues.Add(String.Concat("'", cb.ClientID, "'"))
Next'Output the array to the Literal control (CheckBoxIDsArray)
CheckBoxIDsArray.Text = "<script type=""text/javascript"">" & vbCrLf & _
"<!--" & vbCrLf & _
String.Concat("var CheckBoxIDs = new Array(", String.Join(",", ArrayValues.ToArray()), ");") & vbCrLf & _
"// -->" & vbCrLf & _
"</script>"
End Sub
Protected Sub ZipandEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ZipandEmail.Click
Dim currentRowsFilePath As String'Enumerate the GridViewRows
For index As Integer = 0 To GridView1.Rows.Count - 1
'Programmatically access the CheckBox from the TemplateField
Dim cb As CheckBox = CType(GridView1.Rows(index).FindControl("RowLevelCheckBox"), CheckBox)'If it's checked, then grab something else on the row
If cb.Checked Then
currentRowsFilePath = GridView1.DataKeys(index).Value'Summary.Text &= String.Concat("<li>", currentRowsFilePath, "</li>")
End If
NextSummary.Text &= "</ul>"
End Sub
Protected Sub LogFileUpload(ByVal userID As Integer, ByVal ApplicantID As Integer, ByVal doctype As String, ByVal docname As String, ByVal Docsize As String)
Dim sqlquery As String = "INSERT INTO [Documents] (UserID, ApplicantID, DocType, DocFileName, Docsize, DateUploaded) VALUES (@UserID, @ApplicantID, @DocType, @DocFileName, @Docsize, @DateUploaded) " & "Select Scope_Identity() AS did"Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("sqlConnectionString").ConnectionString)
Dim cmdinsert As New SqlCommand(sqlquery, cn)
cmdinsert.Parameters.Add(New SqlParameter("@UserID", userID))
cmdinsert.Parameters.Add(New SqlParameter("@ApplicantID", Session("ApplicantID")))
cmdinsert.Parameters.Add(New SqlParameter("@DocType", doctype))
cmdinsert.Parameters.Add(New SqlParameter("@DocFilename", docname))
cmdinsert.Parameters.Add(New SqlParameter("@Docsize", Docsize))
cmdinsert.Parameters.Add(New SqlParameter("@DateUploaded", Date.Now))cmdinsert.CommandType = System.Data.CommandType.Text
cmdinsert.Connection = cn
cn.Open()
Dim did As Integer = Convert.ToInt32(cmdinsert.ExecuteScalar())
End Sub
Protected Sub ClearSessionCommand(sender As Object, e As CommandEventArgs)
Session("SSN") = ""
Session("ApplicantID") = ""
Response.Redirect("./app/Mortgage_application_1.aspx", True)
End Sub
End ClassMonday, April 20, 2020 1:30 AM
Answers
-
User288213138 posted
Hi sking,
sking
The checkboxes are working and I can get the row so it should just be a matter of getting the docIDs of all the selected checkboxes into an array, and then all the files can be accessed to be put into a zip file.I'm not sure how to implement this. Will Asp.net take a list of files and stuff them into a file, and zip it up with password protection?According to your description, i made demo for you as a reference.
I created Zip File on the fly in ASP.Net using the DotNetZip Library, and you need to place the Ionic.Zip.Reduced.dll in the BIN Folder.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText="No files available"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:CheckBox ID="chkSelect" runat="server" /> <asp:Label ID="lblFilePath" runat="server" Text='<%# Eval("Value") %>' Visible="false"></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Text" HeaderText="File Name" /> </Columns> </asp:GridView> <br /> <asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="DownloadFiles" /> Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) If Not IsPostBack Then Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/Files/")) Dim files As List(Of ListItem) = New List(Of ListItem)() For Each filePath As String In filePaths files.Add(New ListItem(Path.GetFileName(filePath), filePath)) Next GridView1.DataSource = files GridView1.DataBind() End If End Sub Protected Sub DownloadFiles(ByVal sender As Object, ByVal e As EventArgs) Using zip As ZipFile = New ZipFile() zip.AlternateEncodingUsage = ZipOption.AsNecessary zip.Password = "123" zip.AddDirectoryByName("Files") For Each row As GridViewRow In GridView1.Rows If (TryCast(row.FindControl("chkSelect"), CheckBox)).Checked Then Dim filePath As String = (TryCast(row.FindControl("lblFilePath"), Label)).Text zip.AddFile(filePath, "Files") End If Next Response.Clear() Response.BufferOutput = False Response.ContentType = "application/zip" Response.AddHeader("content-disposition", "attachment; filename=" & "test.zip") zip.Save(Response.OutputStream) Response.[End]() End Using End Sub
Best regards,
Sam
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Monday, April 20, 2020 7:06 AM
All replies
-
User288213138 posted
Hi sking,
sking
The checkboxes are working and I can get the row so it should just be a matter of getting the docIDs of all the selected checkboxes into an array, and then all the files can be accessed to be put into a zip file.I'm not sure how to implement this. Will Asp.net take a list of files and stuff them into a file, and zip it up with password protection?According to your description, i made demo for you as a reference.
I created Zip File on the fly in ASP.Net using the DotNetZip Library, and you need to place the Ionic.Zip.Reduced.dll in the BIN Folder.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText="No files available"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:CheckBox ID="chkSelect" runat="server" /> <asp:Label ID="lblFilePath" runat="server" Text='<%# Eval("Value") %>' Visible="false"></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Text" HeaderText="File Name" /> </Columns> </asp:GridView> <br /> <asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="DownloadFiles" /> Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) If Not IsPostBack Then Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/Files/")) Dim files As List(Of ListItem) = New List(Of ListItem)() For Each filePath As String In filePaths files.Add(New ListItem(Path.GetFileName(filePath), filePath)) Next GridView1.DataSource = files GridView1.DataBind() End If End Sub Protected Sub DownloadFiles(ByVal sender As Object, ByVal e As EventArgs) Using zip As ZipFile = New ZipFile() zip.AlternateEncodingUsage = ZipOption.AsNecessary zip.Password = "123" zip.AddDirectoryByName("Files") For Each row As GridViewRow In GridView1.Rows If (TryCast(row.FindControl("chkSelect"), CheckBox)).Checked Then Dim filePath As String = (TryCast(row.FindControl("lblFilePath"), Label)).Text zip.AddFile(filePath, "Files") End If Next Response.Clear() Response.BufferOutput = False Response.ContentType = "application/zip" Response.AddHeader("content-disposition", "attachment; filename=" & "test.zip") zip.Save(Response.OutputStream) Response.[End]() End Using End Sub
Best regards,
Sam
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Monday, April 20, 2020 7:06 AM -
User-1767698477 posted
Hi Sam,
Thanks for the info. I have downloaded the archive and I managed to figure out where to find the dll file. I have all the file names in the keys. I'm getting the following error. I believe this happens because there are no uploaded documents. When this happens, am I right that asp.net doesn't build the gridview at all and therefore there is no HeaderLevelcheckbox and you get this null reference error? I'm putting everything into an array and passing it to the zip subroutine. How do you avoid getting this error below?
End If Line 93: 'Get the header CheckBox Line 94: Dim cbHeader As CheckBox = CType(GridView1.HeaderRow.FindControl("HeaderLevelCheckBox"), CheckBox) Line 95: Line
[NullReferenceException: Object reference not set to an instance of an object.] users_documents.Gridview1_DataBound(Object sender, EventArgs e) in C:\mortgageloanapply\users\documents.aspx.vb:94 System.Web.UI.WebControls.BaseDataBoundControl.OnDataBound(EventArgs e) +109 System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +165 System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +34 System.Web.UI.WebControls.DataBoundControl.PerformSelect() +151 System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +76 System.Web.UI.WebControls.GridView.DataBind() +10 System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +114 System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +76 System.Web.UI.Control.EnsureChildControls() +97 System.Web.UI.Control.PreRenderRecursiveInternal() +42 System.Web.UI.Control.PreRenderRecursiveInternal() +163 System.Web.UI.Control.PreRenderRecursiveInternal() +163 System.Web.UI.Control.PreRenderRecursiveInternal() +163 System.Web.UI.Control.PreRenderRecursiveInternal() +163 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +906
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Imports System.Web.Security
Imports DataSet1TableAdapters
Imports Ionic.Zip
Partial Class users_documents
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
If Session("username") = Nothing Then
lblName.Text = "You have been logged out due to inactivity - Please login again."
Exit Sub
End If
lblName.Text = Session("Firstname") & " " & Session("Lastname")
Label2.Text = "Uploaded Documents for " & Session("BorFirst") + " " + Session("BorLast")
Label1.Text = ""
End If
If FileUpload1.FileName = "" Then
Exit Sub
End If
End Sub
Protected Sub ViewCommand(sender As Object, e As CommandEventArgs)
Dim file As String = e.CommandArgument.ToString
Response.Redirect("/users/" & Session("path") & "/" & Session("docpath") + file)
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If DDLdocuments.SelectedValue = "Select Document Type" Then
Label1.Text = "You must select a document type"
Label1.Visible = True
Exit Sub
End If
If FileUpload1.HasFile Then
'Uncomment this line to Save the uploaded file
Dim path As String = Session("path") + "/" + Session("docpath") + "/"
'test for pdf and jpg files only
If Microsoft.VisualBasic.Right(FileUpload1.FileName, 4) <> ".pdf" Then
If Microsoft.VisualBasic.Right(FileUpload1.FileName, 4) <> ".jpg" Then
Label1.Text = "You can only upload .pdf or .jpg files"
Label1.Visible = True
Exit Sub
End If
End If
'only allow file names that are under 25 characters
If Len(FileUpload1.FileName) > 25 Then
Label1.Text = "Please shorten your file name to 25 characters or less"
Label1.Visible = True
Exit Sub
End If
'check for duplicate file. Only unique file names in folder allowed
Dim documentsadapter As New DocumentsTableAdapter
Dim tbldocuments As New DataSet1.DocumentsDataTable
tbldocuments = documentsadapter.GetData(CInt(Session("ApplicantID")))
For Each tbldocumentsrow As DataSet1.DocumentsRow In tbldocuments
If FileUpload1.FileName = tbldocumentsrow.DocFileName Then
Label1.Text = "You have already uploaded a file by this name. Please rename your file."
Label1.Visible = True
Exit Sub
End If
Next
Dim filesize As Double = FileUpload1.FileBytes.Length
If filesize > 5242880 Then
Label1.Text = "Only files up to 5MB may be uploaded"
Label1.Visible = True
Exit Sub
End If
Dim sizes As String() = {"B", "KB", "MB"}
Dim sizeinbytes As Double = FileUpload1.FileBytes.Length
Dim order As Integer = 0While sizeinbytes >= 1024 AndAlso order + 1 < sizes.Length
order += 1
sizeinbytes = sizeinbytes / 1024
End WhileDim result As String = String.Format("{0:0.##} {1}", sizeinbytes, sizes(order))
'FileUpload1.SaveAs("C:\mortgageloanapply\users\" & path & FileUpload1.FileName)
Label1.Text = "Received " & FileUpload1.FileName & "<br>Content Type " & FileUpload1.PostedFile.ContentType & " Length " & FileUpload1.PostedFile.ContentLength & " please wait.."
LogFileUpload(Session("UserID"), Session("ApplicantID"), DDLdocuments.SelectedValue, FileUpload1.FileName, result)
GridView1.DataBind()
Else
Label1.Text = "No uploaded file"
End If
Response.AddHeader("REFRESH", "4;URL=documents.aspx")
End Sub
Protected Sub Gridview1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.DataBound
'Each time the data is bound to the grid we need to build up the CheckBoxIDs array
Dim index As String = e.ToString
If index = "" ThenEnd If
'Get the header CheckBox
Dim cbHeader As CheckBox = CType(GridView1.HeaderRow.FindControl("HeaderLevelCheckBox"), CheckBox)'Run the ChangeCheckBoxState client-side function whenever the
'header checkbox is checked/unchecked
cbHeader.Attributes("onclick") = "ChangeAllCheckBoxStates(this.checked);"'Add the CheckBox's ID to the client-side CheckBoxIDs array
Dim ArrayValues As New List(Of String)
ArrayValues.Add(String.Concat("'", cbHeader.ClientID, "'"))For Each gvr As GridViewRow In GridView1.Rows
'Get a programmatic reference to the CheckBox control
Dim cb As CheckBox = CType(gvr.FindControl("RowLevelCheckBox"), CheckBox)'If the checkbox is unchecked, ensure that the Header CheckBox is unchecked
cb.Attributes("onclick") = "ChangeHeaderAsNeeded();"'Add the CheckBox's ID to the client-side CheckBoxIDs array
ArrayValues.Add(String.Concat("'", cb.ClientID, "'"))
Next'Output the array to the Literal control (CheckBoxIDsArray)
CheckBoxIDsArray.Text = "<script type=""text/javascript"">" & vbCrLf & _
"<!--" & vbCrLf & _
String.Concat("var CheckBoxIDs = new Array(", String.Join(",", ArrayValues.ToArray()), ");") & vbCrLf & _
"// -->" & vbCrLf & _
"</script>"
End Sub
Protected Sub ZipandEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ZipandEmail.Click
Dim currentRowDocFileName As String
Dim al As ArrayList = New ArrayList()
'Enumerate the GridViewRows
For index As Integer = 0 To GridView1.Rows.Count - 1
'Programmatically access the CheckBox from the TemplateField
Dim cb As CheckBox = CType(GridView1.Rows(index).FindControl("RowLevelCheckBox"), CheckBox)'If it's checked, then grab something else on the row
If cb.Checked Then
currentRowDocFileName = GridView1.DataKeys(index).Value
Summary.Text &= String.Concat(currentRowDocFilename + ",")
al.Add(currentRowDocFileName)
End If
Next
DownloadFiles(al)
' For Each i In al
' Console.Write("{0} ", i)
'zip the files
' Next i
End Sub
Protected Sub DownloadFiles(ByVal Array As ArrayList)
Using zip As ZipFile = New ZipFile()
zip.AlternateEncodingUsage = ZipOption.AsNecessary
zip.Password = "123"
zip.AddDirectoryByName("Files")
' Dim documentsadapter As New DocumentsTableAdapter
' Dim tbldocuments As New DataSet1.DocumentsDataTable
' tbldocuments = documentsadapter.GetData
'Dim documents As DocumentsTableAdapter
Dim filepath As String = Session("path") + "/" + Session("docpath") + "/"
For Each file In Array
zip.AddFile(filepath + file, "Files")
Next
Response.Clear()
Response.BufferOutput = False
Response.ContentType = "application/zip"
Response.AddHeader("content-disposition", "attachment; filename=" & "test.zip")
zip.Save(Response.OutputStream)
Response.[End]()
End Using
End Sub
Protected Sub LogFileUpload(ByVal userID As Integer, ByVal ApplicantID As Integer, ByVal doctype As String, ByVal docname As String, ByVal Docsize As String)
Dim sqlquery As String = "INSERT INTO [Documents] (UserID, ApplicantID, DocType, DocFileName, Docsize, DateUploaded) VALUES (@UserID, @ApplicantID, @DocType, @DocFileName, @Docsize, @DateUploaded) " & "Select Scope_Identity() AS did"Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("sqlConnectionString").ConnectionString)
Dim cmdinsert As New SqlCommand(sqlquery, cn)
cmdinsert.Parameters.Add(New SqlParameter("@UserID", userID))
cmdinsert.Parameters.Add(New SqlParameter("@ApplicantID", Session("ApplicantID")))
cmdinsert.Parameters.Add(New SqlParameter("@DocType", doctype))
cmdinsert.Parameters.Add(New SqlParameter("@DocFilename", docname))
cmdinsert.Parameters.Add(New SqlParameter("@Docsize", Docsize))
cmdinsert.Parameters.Add(New SqlParameter("@DateUploaded", Date.Now))
cmdinsert.CommandType = System.Data.CommandType.Text
cmdinsert.Connection = cn
cn.Open()
Dim did As Integer = Convert.ToInt32(cmdinsert.ExecuteScalar())
End Sub
Protected Sub ClearSessionCommand(sender As Object, e As CommandEventArgs)
Session("SSN") = ""
Session("ApplicantID") = ""
Response.Redirect("./app/Mortgage_application_1.aspx", True)
End Sub
End ClassTuesday, April 21, 2020 6:01 AM -
User288213138 posted
Hi sking,
I believe this happens because there are no uploaded documents. When this happens, am I right that asp.net doesn't build the gridview at all and therefore there is no HeaderLevelcheckbox and you get this null reference error? I'm putting everything into an array and passing it to the zip subroutine. How do you avoid getting this error below?GridView1.DataBind()You need to bind the datasource to the GridView, such as below code, otherwise, you can't build your Gridview
Dim dt As DataTable = New DataTable() 'You need to fill the data with dt GridView1.DataSource = dt GridView1.DataBind()
Best regards,
Sam
Tuesday, April 21, 2020 8:46 AM -
User-1767698477 posted
The gridview is not filled programatically by creating a datatable and binding it to the gridview. There is a sqldatasouce on the .aspx page which retrieves the filenames from the documents table. But the checkbox in the header and the row level checkboxes are added in the code behind.
So when the page loads, if there are no files found to put into the gridview, I think the Gridview is not created, and this is why the Gridview1_Databound can't add a headerlevelcheckbox . I added this to the top of the sub and put a breakpoint on the End If. When I hover my mouse over e as system.eventargs it says Empty.
Protected Sub Gridview1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.DataBound
'Each time the data is bound to the grid we need to build up the CheckBoxIDs array
Dim index As String = e.ToString
If index = "" Then
End IfDim cbHeader As CheckBox = CType(GridView1.HeaderRow.FindControl("HeaderLevelCheckBox"), CheckBox)
I have resolved the problem by adding If GridView1.HasControls Then. This is stopping the error and also not breaking the checkboxes. I tried using If Gridview1.hasattributes, but while this stopped the error, it broke the checkboxes. I have the zip file program working now.
Protected Sub Gridview1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.DataBound
'Each time the data is bound to the grid we need to build up the CheckBoxIDs array
'Get the header CheckBoxIf GridView1.HasControls Then
Dim cbHeader As CheckBox = CType(GridView1.HeaderRow.FindControl("HeaderLevelCheckBox"), CheckBox)'Run the ChangeCheckBoxState client-side function whenever the
'header checkbox is checked/unchecked
cbHeader.Attributes("onclick") = "ChangeAllCheckBoxStates(this.checked);"'Add the CheckBox's ID to the client-side CheckBoxIDs array
Dim ArrayValues As New List(Of String)
ArrayValues.Add(String.Concat("'", cbHeader.ClientID, "'"))For Each gvr As GridViewRow In GridView1.Rows
'Get a programmatic reference to the CheckBox control
Dim cb As CheckBox = CType(gvr.FindControl("RowLevelCheckBox"), CheckBox)'If the checkbox is unchecked, ensure that the Header CheckBox is unchecked
cb.Attributes("onclick") = "ChangeHeaderAsNeeded();"'Add the CheckBox's ID to the client-side CheckBoxIDs array
ArrayValues.Add(String.Concat("'", cb.ClientID, "'"))
Next
'Output the array to the Literal control (CheckBoxIDsArray)
CheckBoxIDsArray.Text = "<script type=""text/javascript"">" & vbCrLf & _
"<!--" & vbCrLf & _
String.Concat("var CheckBoxIDs = new Array(", String.Join(",", ArrayValues.ToArray()), ");") & vbCrLf & _
"// -->" & vbCrLf & _
"</script>"
End If
End SubTuesday, April 21, 2020 3:56 PM