Browse to a PDF in ASP.NET Web Site Folder - asp.net

I have an ASP.NET Core web site running under IIS on a server. I created a folder and want to display any pdf file in that folder in the browser using the url for the site.
https://example.com/pdf/myfile.pdf
folder structure:
c:\inetpub\wwwroot\mysite\pdf\myfile.pdf - contains pdf files
I enabled Directory Browsing for the site in IIS Manager, but I get a 404 error.
I'm on Window Server 2019 IIS version 10.

I would dispense with folder/directory browsing. You can't control the user experince and UI.
And it just we few lines of code to display the files in a web page, and then have a button to display the pdf in the browser.
So our markup is like this:
<h2>Select a PDF file to view</h2>
<br />
<div style="width:45%">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="table table-hover">
<Columns>
<asp:BoundField DataField="Date" HeaderText="Date" ItemStyle-Width="100px" />
<asp:BoundField DataField="File Name" HeaderText="ID" />
<asp:BoundField DataField="File Size" HeaderText="Size" ItemStyle-Width="100px" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="cmdDownLoad" runat="server" Text="View"
OnClick="cmdDownLoad_Click"
Row = '<%# Container.DataItemIndex %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
And our code to pull files from a folder and shove into the above gridview looks like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
ShowFiles()
End If
End Sub
Sub ShowFiles()
Dim MyTable As New DataTable
MyTable.Columns.Add("Date", GetType(String))
MyTable.Columns.Add("File Size", GetType(String))
MyTable.Columns.Add("File Name", GetType(String))
MyTable.Columns.Add("FullFile", GetType(String))
'Dim strFolder = Server.MapPath("/app_data")
Dim strFolder = "c:\Test4"
Dim MyDir As New DirectoryInfo(strFolder)
Dim MyFiles() As FileInfo = MyDir.GetFiles("*.pdf")
For Each MyFile As FileInfo In MyFiles
Dim oneRow As DataRow = MyTable.Rows.Add
oneRow("Date") = MyFile.LastAccessTime.ToShortDateString
oneRow("File Size") = Int(MyFile.Length / 1024) & " KB"
oneRow("File Name") = MyFile.Name
oneRow("FullFile") = MyFile.FullName
Next
ViewState("MyTable") = MyTable
GridView1.DataSource = MyTable
GridView1.DataBind()
End Sub
The result is thus this:
So, now all we need is the button code to display the pdf in the browser.
This will work:
Protected Sub cmdDownLoad_Click(sender As Object, e As EventArgs)
Dim btn As Button = sender
Dim RowID = btn.Attributes.Item("Row")
Dim MyTable As DataTable = ViewState("MyTable")
With MyTable.Rows(RowID)
ShowPdf(.Item("File Name"), .Item("FullFile"))
End With
End Sub
Sub ShowPdf(strFileOnlyName As String, strFile As String)
Dim pDFData As Byte()
pDFData = File.ReadAllBytes(strFile)
Response.Buffer = False ' //transmitfile self buffers
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
Response.AddHeader("Accept-Header", pDFData.Length.ToString())
Response.AddHeader("Content-Length", pDFData.Length.ToString())
Response.AddHeader("Content-Disposition", "inline; filename=" & strFileOnlyName)
Response.AddHeader("Expires", "0")
Response.AddHeader("Cache-Control", "private")
Response.ContentType = "application/pdf"
Response.AddHeader("Accept-Ranges", "bytes")
Response.BinaryWrite(pDFData)
Response.Flush()
Response.End()
End Sub
So you can click on the button - it will display the PDF in the browser. If you hit back, then you back to the grid, and you can then view another file.

Related

Edit Gridview update issue

I have got a gridview which when you press select on a row it transfers you to another gridview page,
which displays more columns from that table to give more detail about that row.
I know how to do this using:
<asp:HyperLinkField DataNavigateUrlFields="MISAppID" DataNavigateUrlFormatString="ApplicationsDetails.aspx?MISAppID={0}" Text="Select" />
In the 1st Gridview then using a Stored-procedure on the second page it displays the correct row using the ID field.
In my current site on the second page, I have added an edit button that does edit the row correctly in my database but on completion, it breaks the site and I can't work out how to get it to just refresh the gridview
This is the error I get:
Exception Details: System.NotSupportedException: Updating is not
supported by data source 'SqlDataSource1' unless UpdateCommand is
specified.
Is it the case that my BindGrid is missing something or is the way I am using my Stored-procedure?
Here is my VB code:
Public Sub BindGrid() Handles SqlDataSource1.Selecting
End Sub
Protected Sub OnRowEditing(sender As Object, e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
Me.BindGrid()
End Sub
Protected Sub OnRowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
Dim misappId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
Dim application As String = TryCast(row.Cells(2).Controls(0), TextBox).Text
Dim url As String = TryCast(row.Cells(3).Controls(0), TextBox).Text
Dim access_group As String = TryCast(row.Cells(4).Controls(0), TextBox).Text
Dim creator_ein As String = TryCast(row.Cells(5).Controls(0), TextBox).Text
Dim data_location As String = TryCast(row.Cells(6).Controls(0), TextBox).Text
Dim purpose As String = TryCast(row.Cells(7).Controls(0), TextBox).Text
Dim active As String = TryCast(row.Cells(8).Controls(0), TextBox).Text
Dim business_owner As String = TryCast(row.Cells(9).Controls(0), TextBox).Text
Dim area As String = TryCast(row.Cells(10).Controls(0), TextBox).Text
Dim constr As String = ConfigurationManager.ConnectionStrings("myLocalConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("UPDATE tbl_AutomationCompassApplications SET Application = #Application, URL = #URL, Access_Group = #Access_Group, Creator_EIN = #Creator_EIN, Data_location = #Data_location, Purpose = #Purpose, Active = #Active, Business_Owner = #Business_Owner, Area = #Area WHERE MISAppID = #MISAppID")
cmd.Parameters.AddWithValue("#MISAppID", misappId)
cmd.Parameters.AddWithValue("#Application", application)
cmd.Parameters.AddWithValue("#URL", url)
cmd.Parameters.AddWithValue("#Access_Group", access_group)
cmd.Parameters.AddWithValue("#Creator_EIN", creator_ein)
cmd.Parameters.AddWithValue("#Data_location", data_location)
cmd.Parameters.AddWithValue("#Purpose", purpose)
cmd.Parameters.AddWithValue("#Active", active)
cmd.Parameters.AddWithValue("#Business_Owner", business_owner)
cmd.Parameters.AddWithValue("#Area", area)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
GridView1.EditIndex = -1
Me.BindGrid()
End Sub
Ok, say we have a list of hotels - we want to display them, and then click on a row to eit.
(and you writing WAY too much code here).
So, lets say we drop in a gridview. Use the connection wizard - let it generate the markup.
THEN REMOVE the data source on the page, remove the datasource property of the gridview.
So, in less time then it takes me to write above? We have this markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="cmdView" runat="server" Text="Edit"
PK = '<%# Container.DataItemIndex %>' OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
</asp:GridView>
Note the cool trick I used to get the PK row index.
When you are looking at the grid, you can't double click on the button to wire up a event (code behind), but you CAN DO THIS!!!!
Note VERY care full in above - I typed in OnClick "=", when you HIT "=", then NOTE the inteli-sense that popped up - the create NEW event is what we need. Click on create new event - NOTHING seems to happen, but if we NOW go to code behind, we have a code stub for the button!!!
And note how I needed/wanted the PK row value - so I just shoved in and created my OWN custom attribute for that button. ("PK").
Ok, so our code to load up the grid is now this - and I included the button click code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Dim strSQL As String
strSQL = "SELECT * from tblHotels Order by HotelName"
Using cmdSQL As New SqlCommand(strSQL, New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
Dim MyTable As New DataTable
MyTable.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = MyTable
GridView1.DataBind()
Session("MyTable") = MyTable
End Using
End Sub
Protected Sub cmdView_Click(sender As Object, e As EventArgs)
Dim MyBtn As Button = sender
Session("RowID") = MyBtn.Attributes.Item("PK")
Response.Redirect("~/EditHotel.aspx")
End Sub
Look how clean and simple the above is!!! I find this as easy say as MS-Access coding!!!
Ok, so the grid now looks like this:
Note the button click code.
So, our markup is this for the new page (to edit hte ONE row).
<div style="float:left;width:20%">
<div style="text-align:right">
First Name :<asp:TextBox ID="txtFirstname" runat="server" Width="150"></asp:TextBox> <br />
Last Name :<asp:TextBox ID="txtLastname" runat="server" Width="150"></asp:TextBox> <br />
Hotel Name :<asp:TextBox ID="txtHotel" runat="server" Width="150"></asp:TextBox> <br />
City :<asp:TextBox ID="txtCity" runat="server" Width="150"></asp:TextBox> <br />
Active :<asp:CheckBox ID="Active" runat="server" Width="150"></asp:CheckBox>
</div>
</div>
<div style="clear:both">
<br />
<asp:Button ID="cmdSave" runat="server" Text ="Save " />
<asp:Button ID="cmdCancel" runat="server" Text="Cancel" Style="margin-left:20px" />
</div>
</form>
and it looks like this:
and the load code and save button code for this page?
This:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LoadInfo()
End If
End Sub
Sub LoadInfo()
Dim MyTable As DataTable = Session("MyTable")
Dim MyRow As DataRow = MyTable.Rows(Session("RowID"))
txtFirstname.Text = MyRow("FirstName")
txtLastname.Text = MyRow("LastName")
txtCity.Text = MyRow("City")
txtHotel.Text = MyRow("HotelName")
Active.Checked = MyRow("Active")
End Sub
Protected Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
Dim MyTable As DataTable = Session("MyTable")
Dim MyRow As DataRow = MyTable.Rows(Session("RowID"))
MyRow("FirstName") = txtFirstname.Text
MyRow("LastName") = txtLastname.Text
MyRow("City") = txtCity.Text
MyRow("HotelName") = txtHotel.Text
MyRow("Active") = Active.Checked
Using cmdSQL As New SqlCommand("SELECT * from tblHotels where ID = 0",
New SqlConnection(My.Settings.TEST3))
Dim da As New SqlDataAdapter(cmdSQL)
Dim cmdUpdate As New SqlCommandBuilder(da)
da.Update(MyTable)
End Using
Response.Redirect("~/MyTours.aspx")
End Sub
Again, look how easy, clean and readable the code is.
Study the above example - you see that you don't need all that parameters code, and you see how little code is in fact required to select a row - jump to page to edit, and then you hit save - update the data and jump back to the grid row page.

SQL connection will not display on gridview

I have a website and when a user logs in they can see their own information (username and a grid containing information about their medicines). This did load but now since I have moved it only loads the logged in user's username and does not display the grid that held their medicine information.I moved my project file from my laptop on to my college computer and ensured to change the location of where I was loading the data from :
Previously
"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Laura\Final_proj\App_Data\surgerydb.mdf;Integrated Security=True;Connect Timeout=30"
Now:
"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Connect Timeout=30"
This should work as the login uses the same data directory source and logs the user in. They are then redirected to the user.aspx page but now the grid does not display
user.aspx page (the query doesnt seem to be even running on this:
Imports System.Data.SqlClient
Imports System.Data
Partial Class Pages_user
Inherits System.Web.UI.Page
Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs)
If Not IsPostBack Then
Dim conn As New System.Data.SqlClient.SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Connect Timeout=30")
Dim cmdstring As String = "SELECT md.MedicineId, md.Name, md.Purpose, md.Instrcutions, DoctorId " +
"FROM Patient pt INNER JOIN prescription pr ON pt.PatientId = pr.PatientId " +
"INNER JOIN medicine md ON md.MedicineId = pr.MedicineId Where pt.PatientId = #PatientId"
Dim dt As New System.Data.DataTable()
Dim da As New System.Data.SqlClient.SqlDataAdapter(cmdstring, conn)
da.SelectCommand.Parameters.Add("#PatientId", System.Data.SqlDbType.Int).Value = CInt(Session("PatientId").ToString())
conn.Open()
da.Fill(dt)
conn.Close()
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Sub
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "UpdateMedicine" Then
Dim medecineID As Integer = Integer.Parse(e.CommandArgument.ToString())
End If
End Sub
The grid:
<asp:Content ID="Content3" ContentPlaceHolderID="contentbody" runat="Server">
<p>
Please Select Your Medication
</p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Select" CommandName="UpdateMedicine" CommandArgument='<%# Eval("MedicineId") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Purpose" HeaderText="Purpose" />
<asp:BoundField DataField="Instrcutions" HeaderText="Instructions" />
</Columns>
</asp:GridView>
</asp:Content>
What it looked like previously:
Hopefully someone can help
kind regards
After discussion, it turns out that Page_Load was not called, since AutoEventWireup was turned off and the event handler was not specified in code-behind. Either one of these two changes should work:
The event to handle can be specified in code-behind:
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
or AutoEventWireup can be turned on in the markup file:
<%# Page AutoEventWireup="true" ... %>

How to download image/pdf file from database using Gridview's linkbutton?

Here is my problem. I have a user control that will download a binary file (image, pdf etc.) using a link button in gridview.
<asp:GridView Visible="true" ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"/>
<asp:BoundField DataField="FileName" HeaderText="File Name"/>
<asp:TemplateField HeaderText="Action" ItemStyle-HorizontalAlign = "Center">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" OnClick="DeleteFile" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
Protected Sub DownloadFile(sender As Object, e As EventArgs)
Dim id As Integer = Integer.Parse(TryCast(sender, LinkButton).CommandArgument)
Dim bytes As Byte()
Dim fileName As String, contentType As String
Using con As New SqlConnection(DataSource.ConnectionString)
Using cmd As New SqlCommand()
cmd.CommandText = "select FileName, PatImage, FileType from DB where Id=#Id"
cmd.Parameters.AddWithValue("#Id", id)
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
sdr.Read()
bytes = DirectCast(sdr("PatImage"), Byte())
contentType = sdr("FileType").ToString()
fileName = sdr("FileName").ToString()
End Using
con.Close()
End Using
End Using
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = contentType
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName)
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
But this is not working if I have an UpdatePanel in my parent aspx page. So i googled and I found an answer; that is to place a code in RowDataBound:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim lb As LinkButton = TryCast(e.Row.FindControl("lnkDownload"), LinkButton )
ScriptManager.GetCurrent(Me.Page).RegisterAsyncPostBackControl(lb)
End Sub
And a new error occurred. That is I can't find my linkButton inside my GridView using my code in my RowDataBound.
So i googled again, and i found out that i should add a property to my aspx page ClientIDMode="AutoID". But this is only working on framework 4.x. And I couldn't do that 'cause im currently using 3.5. Are there any remedies in my current situation?
A already found an answer, I just changed my RowDataBound content, refer to the code:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim LButton = CType(e.Row.FindControl("lnkDownload"), System.Web.UI.WebControls.LinkButton)
Dim scriptManager__1 = ToolkitScriptManager.GetCurrent(Me.Page)
If scriptManager__1 IsNot Nothing Then
scriptManager__1.RegisterPostBackControl(LButton)
End If
End If
End Sub

How to automatically select a file to FileUpload on page load?

I want to automatically select a file on page load to my FileUpload1. I tried searching but I cant find any related instances. I want to do somethhing like this.
Private Sub WebForm1_Load(sender As Object, e As EventArgs) Handles Me.Load
FileUpload1.setfile("D:\file\Test.Wav")
End Sub
Because my program is to record a sound (wav file) and it saves to a specific folder. And afterwards, I can select the recorded file and upload/save the file to the database.
When you click button_1, it records a sound using the mic. Then you will button_2 to stop and save the recorded sound.
But what i wanted to do is after clicking the button_2, it will stop and save the recording AND asynchronously it uploads the file to the database.
Here is the code: .VB file
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.Devices
Imports Microsoft.VisualBasic
Imports System.Runtime.InteropServices
Imports System.Text
Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
Using br As New BinaryReader(FileUpload1.PostedFile.InputStream)
Dim bytes As Byte() = br.ReadBytes(CInt(FileUpload1.PostedFile.InputStream.Length))
Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(strConnString)
Using cmd As New SqlCommand()
cmd.CommandText = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)"
cmd.Parameters.AddWithValue("#Name", Path.GetFileName(FileUpload1.PostedFile.FileName))
cmd.Parameters.AddWithValue("#ContentType", "audio/mpeg3")
cmd.Parameters.AddWithValue("#Data", bytes)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(strConnString)
Using cmd As New SqlCommand()
cmd.CommandText = "select Id, Name from tblFiles"
cmd.Connection = con
con.Open()
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
con.Close()
End Using
End Using
End Sub
<DllImport("winmm.dll")> _
Private Shared Function mciSendString(ByVal command As String, ByVal buffer As StringBuilder, ByVal bufferSize As Integer, ByVal hwndCallback As IntPtr) As Integer
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim i As Integer
i = mciSendString("open new type waveaudio alias capture", Nothing, 0, 0)
i = mciSendString("record capture", Nothing, 0, 0)
Label1.Text = "Recording"
Label1.BackColor = Drawing.Color.Green
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
Dim i As Integer
i = mciSendString("save capture " & "D:\file\Test.Wav", Nothing, 0, 0)
i = mciSendString("close capture", Nothing, 0, 0)
Label1.Text = "Idle"
Label1.BackColor = Drawing.Color.Yellow
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub WebForm1_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
aspx.file
<form runat="server">
<asp:Button ID="Button1" runat="server" Text="Record" />
<asp:Button ID="Button2" runat="server" Text="Save" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" RowStyle- BackColor="#A1DCF2" Font-Names = "Arial" Font-Size = "10pt"
HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">
<Columns>
<asp:BoundField DataField="Name" HeaderText="FileName" />
<asp:TemplateField>
<ItemTemplate>
<object type="application/x-shockwave-flash" data='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'
width="240" height="20" id="dewplayer">
<param name="wmode" value="transparent" />
<param name="movie" value='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'/>
<object>
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField DataNavigateUrlFields="Id" Text = "Download" DataNavigateUrlFormatString = "~/File.ashx?Id={0}" HeaderText="Download" />
</Columns>
</asp:GridView>
I don't think it is possible due to security reasons. Imagine you visit a random site and it automatically starts uploading files from your local file system without your knowledge/permission.
The input type file control requires the user to select a file to upload, so there is no way you can do it programmatically.

ASP.net: GridView columns repeating after paging

I have a GridView that has it's columns added dynamically in codebehind. I've added paging to the GridView, and it works, but when it goes to the next page, it adds the columns again.
So the GridView starts out with 2 columns (Last Name and First Name) added from codebehind. Then I go to it's next page, and it properly loads the next page of results, but now with 4 columns (Last Name, First Name, Last Name, First Name).
What am I doing wrong here?
Here's the code for the GridView:
<asp:GridView id="GridView3" runat="server" AutoGenerateColumns="False"
EmptyDataText="There are no data records to display."
AllowPaging="True"
OnPageIndexChanging="GridView3_PageIndexChanging"
CssClass="GridViewStyle" GridLines="None" Width="100%">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="EmplID"
DataNavigateUrlFormatString="EmployeeProfile.aspx?EmplID={0}"
DataTextField="EmplID"
DataTextFormatString= "<img src='Images/icons/document-search-result.png' alt='View'/> <u>View</u>" >
<ControlStyle CssClass="titleLinksB" />
<ItemStyle Wrap="False" />
</asp:HyperLinkField>
</Columns>
</asp:GridView>
Here's the code for the codebehind:
Private Sub loadDynamicGrid()
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim lastName As String
Dim linkText As String
lastName = Request.QueryString("lastName")
connetionString = ConfigurationManager.ConnectionStrings("dbConnectionString").ConnectionString.ToString()
sql = "SELECT * FROM [EmployeeList] Where [lastname] like '" & lastName & "%' order by lastname"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
Dim curLastName As New BoundField
curLastName.HeaderText = "Last Name"
curLastName.DataField = "LastName"
GridView3.Columns.Insert(0, curLastName)
Dim curFirstName As New BoundField
curFirstName.HeaderText = "First Name"
curFirstName.DataField = "FirstName"
GridView3.Columns.Insert(1, curFirstName)
GridView3.Visible = True
GridView3.DataSource = ds
GridView3.DataBind()
adapter.Dispose()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
And finally the Paging code:
Protected Sub GridView3_PageIndexChanging(ByVal sender As [Object], ByVal e As GridViewPageEventArgs)
GridView3.PageIndex = e.NewPageIndex
GridView3.DataBind()
End Sub
Any help is greatly appreciated!
I assume that you're calling loadDynamicGrid on every postback and not only If Not Page.IsPostBack.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
loadDynamicGrid()
End If
End Sub

Resources