How to open pdf file in new tab in asp.net(vb)? - asp.net

I want to show my pdf file in new tab when I click the button of gridview. How can I display? Please someone help me .
This is my code.
'my gridview button click event
Protected Sub btnDisplay_Click(sender As Object, e As EventArgs)
Dim grdrow As GridViewRow = CType((CType(sender, Button)).NamingContainer, GridViewRow)
'I save pdf with datetime but showing file name without datetime on screen so I need to
'combine again when I need to open the file from upload folder
Dim dtime As DateTime = grdrow.Cells(2).Text
Dim fname As String = lblFileName.Text.Split(".").First + "_" +
dtime.ToString("yyyyMMddHHmmss") + ".pdf"
Dim FilePath As String = Server.MapPath("~/uploads/" & fname)
Dim User As WebClient = New WebClient()
Dim FileBuffer As Byte() = User.DownloadData(FilePath)
If FileBuffer IsNot Nothing Then
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", FileBuffer.Length.ToString())
Response.BinaryWrite(FileBuffer)
End If
End Sub
--Edit--
I got some idea and it did work for me.
I added some script to open new tab.
html,gridview
//javascript
<script type="text/javascript">
function openInNewTab() {
window.document.forms[0].target = '_blank';
setTimeout(function () { window.document.forms[0].target = ''; }, 0);
}
</script>
<asp:BoundField DataField="FileName" HeaderText="Filename" ItemStyle-Width="200" HtmlEncode="false"><ItemStyle Width="200px"></ItemStyle></asp:BoundField>
<asp:BoundField DataField="Process" HeaderText="Process" ItemStyle-Width="200" HtmlEncode="false"><ItemStyle Width="200px"></ItemStyle></asp:BoundField>
<asp:TemplateField ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="btnDisplay" runat="server" Text="Display" OnClick="btnDisplay_Click" OnClientClick="openInNewTab();" Visible='<%# If(Eval("Process").ToString() = "Uploaded", True, False) %>'></asp:Button>
</ItemTemplate>
</asp:TemplateField>
Main.aspx
Protected Sub btnDisplay_Click(sender As Object, e As EventArgs)
Dim grdrow As GridViewRow = CType((CType(sender, Button)).NamingContainer, GridViewRow)
Dim fname As String = grdrow.Cells(2).Text
'pdf Display
Session("pdfname") = fname
Response.Redirect("GeneratePDF.aspx")
End Sub
GeneratePDF.aspx
<form id="form1" runat="server">
<div style ="Display: Inline-block;float: left;">
<asp:Literal ID="ltEmbed" runat="server" />
</div>
</form>
GeneratePDF.aspx.vb
Dim pdf_name As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.Title = "PDF DISPLAY"
pdf_name = Session("pdfname")
Dim embed As String = "<object data=""{0}"" type=""application/pdf"" width=""2000px"" height=""1000px"">"
embed += "If you are unable to view file, you can download from here"
embed += " or download <a target = ""_blank"" href = ""http://get.adobe.com/reader/"">Adobe PDF Reader</a> to view the file."
embed += "</object>"
ltEmbed.Text = String.Format(embed, ResolveUrl("~/uploads/" + pdf_name))
End Sub

First use hyperlink instead of Button and make target =_blank. Then on Page Load of new aspx write code for generating PDF.
'HTML CODE
<asp:HyperLink ID="btnDisplay" runat="server" Text="Open PDF" Target ="_blank" NavigateUrl="~/WBP/GeneratePDF.aspx"></asp:HyperLink>
'SERVER CODE
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Dim dtime As DateTime = DateTime.Now.ToString()
Dim fname As String = "pdffile_" +
dtime.ToString("yyyyMMddHHmmss") + ".pdf"
Dim FilePath As String = Server.MapPath("writereaddata/" & fname)
Dim User As WebClient = New WebClient()
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Dim pdfDoc As New Document(PageSize.A4, 10, 10, 8, 2)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream)
Dim sr As New StringReader(sw.ToString())
pdfDoc.Open()
Dim pthd As Paragraph = New Paragraph("WELCOME TO PDF FILE", New Font(Font.TIMES_ROMAN, 11, Font.BOLD, Color.BLACK))
pdfDoc.Add(pthd)
htmlparser.Parse(sr)
pdfDoc.Close()
HttpContext.Current.Response.Write(pdfDoc)
HttpContext.Current.Response.End()
End Sub

i think you are missing something, add Response.End() at the end of the if statement
If FileBuffer IsNot Nothing Then
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", FileBuffer.Length.ToString())
Response.BinaryWrite(FileBuffer)
Response.End()
End If
if it doesnt work, there must be an issue on the Html

Related

How do I get last modified date of website

I have website URL's in a DataGridView Cell when I click on the Cell the website is loaded in Chrome. I am using VS 2019 and VB.Net only I do not have ASP.Net installed.
I have tried a bunch of different concepts from some SO post that go back to 2011
With very little success I found one function that looked workable but no results I will post that code.
My question is How do I get last modified date of website?
If using VB.Net ONLY is not workable point me to a reference for other tools needed.
Public Property DateTime_LastModified As String
Dim webPAGE As String
This code is inside a click event for the DataGridView
ElseIf gvTxType = "View" Then
webPAGE = row.Cells(2).Value.ToString()
'Modified: <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Process.Start(webPAGE)
GetDateTimeLastModified(requestUriString)
Label1.Text = DateTime_LastModified
'Dim strPath As String = webPAGE + "javascript : alert(document.lastModified)"
'Dim strPath As String = Request.PhysicalPath
'Server.MapPath
'Label1.Text = System.IO.File.GetLastWriteTime(webPAGE).ToString()
'Label1.Text = strPath '"Modified: " + System.Web.UI.GetLastWriteTime(strPath).ToString()
'Label1.Text = strPath + "Modified:" + System.MapPath.Request.ServerVariables.Get("SCRIPT_NAME")
'Process.Start(webPAGE)
Here is the Edit I tried from the Answer
Public Class GetURLdate1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strURL As String
strURL = TextBox1.Text
Dim client = New HttpClient()
Dim msg As New HttpRequestMessage(HttpMethod.Head, strURL)
Dim resp = client.SendAsync(msg).Result
Dim strLastMod As String = resp.Content.Headers.LastModified.ToString
MsgBox("Last mod as string date" & vbCrLf & strLastMod)
'Dim lastMod As DateTime = CDate(strLastMod)
'MsgBox(lastMod)
End Sub
Private Sub GetURLdate1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "https://www.youtube.com/c/stevinmarin/videos"
'"https://stackoverflow.com/questions/70825821/how-do-i-get-last-modified-date-of-website"
End Sub
Returns NO Value for strLastMod
Ok, so it not clear if you need a routine to go get all the URL's in the grid, and update the last updated for each site/url?
Or are you looking to ONLY update the site WHEN you click on the button to jump to the site?
It is easy to do both.
I mean, say we have this markup - drop in a gridview (I let the wizards created it).
I then blow out the datasoruce control, and then remove the data soruce ID setting from the GV
So, I have this markup:
<div style="padding:35px">
<asp:GridView ID="GridView1" runat="server" CssClass="table" Width="65%"
AutoGenerateColumns="False" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="Url" HeaderText="Url" ItemStyle-Width="500" />
<asp:BoundField DataField="LastUpDated" HeaderText="Last UpDated" />
<asp:BoundField DataField="LastVisit" HeaderText="Last Visit" />
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="cmdJump" runat="server" Text="View" CssClass="btn"
OnClick="cmdJump_Click"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="cmdGetAll" runat="server" Text="Upate all Last updated" CssClass="btn" />
</div>
Ok, and my code to load the gv is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Using conn = New SqlConnection(My.Settings.TEST4)
Using cmdSQL = New SqlCommand("SELECT * FROM tblSites", conn)
Dim rstData As New DataTable
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rstData
GridView1.DataBind()
End Using
End Using
End Sub
And now we have this:
Ok, so just dropped in a plane jane button into the GV. When I click on that button, I will update the last visit - not clear if you ALSO want this to update the last update for the given url?
we can do both.
So, out simple button we dropped? Well, lets have it update the last time we visit (click) to jump to the site).
Protected Sub cmdJump_Click(sender As Object, e As EventArgs)
Dim cmdView As Button = sender
Dim gRow As GridViewRow = cmdView.NamingContainer
Dim PKID As Integer = GridView1.DataKeys(gRow.RowIndex).Item("ID")
' udpate with last visit click
Using conn = New SqlConnection(My.Settings.TEST4)
Using cmdSQL = New SqlCommand("update tblSites SET LastVisit = #Visit WHERE ID = #ID", conn)
conn.Open()
cmdSQL.Parameters.Add("#Visit", SqlDbType.DateTime).Value = Date.Now
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID
cmdSQL.ExecuteNonQuery()
End Using
End Using
' Now jump to that url
Response.Redirect(gRow.Cells(0).Text)
End Sub
And the button to go fetch and update all last updates (every row) of the given URL's cna be this:
Protected Sub cmdGetAll_Click(sender As Object, e As EventArgs) Handles cmdGetAll.Click
Using conn = New SqlConnection(My.Settings.TEST4)
Using cmdSQL = New SqlCommand("SELECT * FROM tblSites", conn)
Dim rstData As New DataTable
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
For Each OneRow As DataRow In rstData.Rows
Dim client = New HttpClient()
Dim msg As New HttpRequestMessage(HttpMethod.Head, OneRow("Url").ToString)
Dim resp = client.SendAsync(msg).Result
Dim lastMod As DateTimeOffset? = resp.Content.Headers.LastModified
OneRow("LastUpDated") = lastMod.Value.ToString
Next
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
da.Update(rstData)
' now re-load grid
LoadGrid()
End Using
End Using
End Sub
So, the above has the code to update the data for all URL's.
But, your question seems to suggest that when you click on the GV row button, you ALSO want to get/save/update the given row of the GV with the last update information from the web site url?
Ok, then, we modify our click code, to update both our last click visit, and then also get that web site last update information.
So, just change the button click row code to this then:
Protected Sub cmdJump_Click(sender As Object, e As EventArgs)
Dim cmdView As Button = sender
Dim gRow As GridViewRow = cmdView.NamingContainer
Dim PKID As Integer = GridView1.DataKeys(gRow.RowIndex).Item("ID")
Dim client = New HttpClient()
Dim msg As New HttpRequestMessage(HttpMethod.Head, gRow.Cells(0).Text)
Dim resp = client.SendAsync(msg).Result
Dim lastMod As DateTime = resp.Content.Headers.LastModified.ToString
' udpate with last visit click, and also get laste update from web site
Using conn = New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
"update tblSites SET LastVisit = #Visit,LastUpdated = #LastUpDate WHERE ID = #ID"
Using cmdSQL = New SqlCommand(strSQL, conn)
conn.Open()
cmdSQL.Parameters.Add("#Visit", SqlDbType.DateTime).Value = Date.Now
cmdSQL.Parameters.Add("#LastUpDate", SqlDbType.DateTime).Value = lastMod
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID
cmdSQL.ExecuteNonQuery()
End Using
End Using
' Now jump to that url
Response.Redirect(gRow.Cells(0).Text)
End Sub
Edit: Not using asp.net
I now see in your post that you suggest you are not using asp.net. However, the above code would work near the same if you are say using a vb.net desktop + gridview. In other words, the code should be similar, and that includes the code to get that web site date.
so, you need to use follow hyper link, but the code to get the date from the web site, and even your general form layout for desktop. The results - even the way your gird looks will thus be very similar to the above web page, the overall idea here thus applies equal well to desktop or web based. I mean, if you have visual studio installed, then you could try above - as VS does install the web bits and parts for you.
Edit #2 - code to get last modified date.
There is NOT some process start, NEVER suggested to use as such. The code you need is thus this:
webPAGE = row.Cells(2).Value.ToString()
Dim client = New HttpClient()
Dim msg As New HttpRequestMessage(HttpMethod.Head,webPAGE)
Dim resp = client.SendAsync(msg).Result
Dim lastMod As DateTime = resp.Content.Headers.LastModified.ToString
MsgBox("DATE " & lastMod)
Edit#3: Code as win forms
Ok, so we create a blank new windows form.
Drop in a text box, drop in a button.
We have this code:
Imports System.Net.Http
Public Class GetURLdate1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strURL As String
strURL = TextBox1.Text
Dim client = New HttpClient()
Dim msg As New HttpRequestMessage(HttpMethod.Head, strURL)
Dim resp = client.SendAsync(msg).Result
Dim strLastMod As String = resp.Content.Headers.LastModified.ToString
MsgBox("Last mod as string date" & vbCrLf & strLastMod)
Dim lastMod As DateTime = strLastMod
MsgBox(lastMod)
End Sub
Private Sub GetURLdate1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text =
"https://stackoverflow.com/questions/70825821/how-do-i-get-last-modified-date-of-website"
End Sub
So, I used THIS web page for the url.
When I run this form - click on button, I see this:

When I download the Excel File from the website I am unable to see it's contents

I have a website in Asp.net wherein I have implemented a button to Store GridView in an Excel Format but when I open the file I am unable to see the actual contents of the GridView and I can only see the column headings. I have used three following imports after installing EPPlus via NuGet Package Manager.
using OfficeOpenXml;
using System.IO;
using WebFormsTest.Models;
My code behind is as follows
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
Dim GetProducts As Object = Nothing
GridView6.DataSource = GetProducts
GridView6.DataBind()
End If
End Sub
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Response.Clear()
Dim products = GetProducts()
GridView6.DataSource = products
GridView6.DataBind()
Dim excel As ExcelPackage = New ExcelPackage
Dim workSheet = excel.Workbook.Worksheets.Add("Products")
Dim totalCols = GridView6.Rows(0).Cells.Count
Dim totalRows = GridView6.Rows.Count
Dim headerRow = GridView6.HeaderRow
worksheet.Cells["A1"].LoadFromCollection(GetProducts())
Dim memoryStream = New MemoryStream
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=products.xlsx")
excel.SaveAs(memoryStream)
memoryStream.WriteTo(Response.OutputStream)
Response.Flush()
Response.End()
End Sub
Public Function GetProducts() As List(Of Product)
End Function
My Aspx button is as given below
<asp:Button ID="Button3" runat="server" Text="EXPORT RTD TO EXCEL" onclick="Button3_Click" BackColor="#FF9966" CssClass="btn btn-large" Font-Bold="True"/>
Editing the code behind to the following solves this problem and via the Nuget Package Manager we can download ClosedXML so that it includes the following import
Imports ClosedXML.Excel
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Dim dt As New DataTable("GridView_Data")
For Each cell As TableCell In GridView5.HeaderRow.Cells
dt.Columns.Add(cell.Text)
Next
For Each row As GridViewRow In GridView5.Rows
dt.Rows.Add()
For i As Integer = 0 To row.Cells.Count - 1
dt.Rows(dt.Rows.Count - 1)(i) = row.Cells(i).Text
Next
Next
Dim wb As New XLWorkbook
wb.Worksheets.Add(dt)
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment;filename=GridViewPOLQA.xlsx")
Using MyMemoryStream As New MemoryStream()
wb.SaveAs(MyMemoryStream)
MyMemoryStream.WriteTo(Response.OutputStream)
Response.Flush()
Response.[End]()
End Using
End Sub
I don't know what the datatype is of products, but why not bind it directly to the sheet?
worksheet.Cells["A1"].LoadFromCollection(GetProducts());
And you are not seeing the contents of the GridView on Button3_Click because you are sending an Excel file to the client (by setting the Response.ContentType), not an updated html page where the GridView has been filled with products.
Quick demo translated from C# to vb
Dim excelPackage As ExcelPackage = New ExcelPackage
Dim worksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1")
worksheet.Cells("A1").LoadFromCollection(GetProducts())
Dim bin() As Byte = excelPackage.GetAsByteArray
Response.ClearHeaders
Response.Clear
Response.Buffer = true
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-length", bin.Length.ToString)
Response.AddHeader("content-disposition", "attachment; filename=""mySheet.xlsx"""")", Response.OutputStream.Write(bin, 0, bin.Length))
Response.Flush
HttpContext.Current.ApplicationInstance.CompleteRequest

how to find the button id inside the Gridview which is in update panel?

i am not able to find the id of the update button is thee any way to
find the update button id which is inside the gridview and the grid is
inside the update panel.
Script register is written is page load. i am writing this so as
currently update button is firing on second click
ASPX code
<asp:UpdatePanel ID="UpdatePanelSubMeter" runat="server">
<ContentTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" Style="background-color: #B2DE94; width: 40px" CausesValidation="false" runat="server" OnClientClick="return fnCheck(this);" Text="Update" CommandName="Update" />
</EditItemTemplate>
</asp:UpdatePanel>
vb.net code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.ErrorLabel.Text = String.Empty
Me.ErrorLabel.Visible = False
Dim pageName = HttpContext.Current.Request.Url.AbsoluteUri
If (Not Page.IsPostBack) Then
tblNAbers.Visible = True
BindBLDGDropDown("adonepudi")
End If
For Each gvr As GridViewRow In GridSubMeter.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim button As Button = CType(gvr.FindControl("btn_Update"), Button)
If Not (button Is Nothing) Then
ScriptManager.GetCurrent(Me).RegisterPostBackControl(button)
end sub
Protected Sub ddlBldgId_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlBldgId.SelectedIndexChanged
If ddlBldgId.SelectedItem.Value != -1 Then
BindGridSubMeter()
end sub
Protected Sub BindGridSubMeter()
Dim conMRI As New ConnectionMRI()
Dim ds As DataSet = conMRI.NabersSubMetergetData(ddlBldgId.SelectedItem.Value, ddlRating.SelectedItem.Value)
TextExclusions.Text = ds.Tables(1).Rows(0).Item(0).ToString()
UpdatePanelExclusions.update()
With GridSubMeter
.DataSource = ds.Tables(0)
.DataBind()
End With
End Sub
Protected Sub GridSubMeter_RowEditing(sender As Object, e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridSubMeter.RowEditing
GridSubMeter.EditIndex = e.NewEditIndex
Me.BindGridSubMeter()
End Sub
Protected Sub GridSubmeter_PageIndexChanging(sender As Object, e4 As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridSubMeter.PageIndexChanging
GridSubMeter.PageIndex = e4.NewPageIndex
Me.BindGridSubMeter()
End Sub
Protected Sub GridSubMeter_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridSubMeter.RowUpdating
Dim txtMeterIdn As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txtMeterIdn"), TextBox)
Dim txCTFact As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txCTFact"), TextBox)
Dim txReadStartDate As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txReadStartDate"), TextBox)
Dim txReadEndDate As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txReadEndDate"), TextBox)
Dim txStartKwh As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txStartKwh"), TextBox)
Dim txEndKwh As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txEndKwh"), TextBox)
Dim txBillPer As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txBillPer"), TextBox)
Dim MeterIdn As String = txtMeterIdn.Text.Trim.ToString()
Dim CTFact As Decimal = Convert.ToDecimal(txCTFact.Text)
Dim ReadStartDate As Date = Date.Parse(txReadStartDate.Text)
Dim ReadEndDate As Date = Date.Parse(txReadEndDate.Text)
Dim StartKwh As Decimal = Convert.ToDecimal(txStartKwh.Text)
Dim EndKwh As Decimal = Convert.ToDecimal(txEndKwh.Text)
Dim billper As Decimal = Convert.ToDecimal(txBillPer.Text)
Dim leasid As String = GridSubMeter.Rows(e.RowIndex).Cells(0).Text.Trim.ToString()
Dim suitid As String = GridSubMeter.Rows(e.RowIndex).Cells(1).Text.Trim.ToString()
Dim occupant As String = GridSubMeter.Rows(e.RowIndex).Cells(2).Text.Trim.ToString()
GridSubMeter.EditIndex = -1
Dim conMRI As New ConnectionMRI()
conMRI.NaberSubmeter(ddlBldgId.SelectedItem.Value, leasid, suitid, occupant, MeterIdn, CTFact, ReadStartDate, ReadEndDate, StartKwh, EndKwh, billper)
Me.BindGridSubMeter()
End Sub
Try removing
For Each gvr As GridViewRow In GridSubMeter.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim button As Button = CType(gvr.FindControl("btn_Update"), Button)
If Not (button Is Nothing) Then
ScriptManager.GetCurrent(Me).RegisterPostBackControl(button)
from page load and paste it in BindGridSubMeter at the end.
Try this
For Each gr As GridViewRow In Grid_Records.Rows
Dim bt As Button = DirectCast(gr.Cells(0).FindControl("btn_Update"), Button)
Dim here As bt.properties
Next

sending a variable from code-behind to .aspx

How I can send a variable from code-behaind to .aspx file :
code-behind:
variable FilePathName
.aspx:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Text="Label"></asp:TextBox>
<frameset cols="100%,*">
<frame name="main" target="main" src="FilePathName">
</frameset>
</div>
</form>
How I can send FilePathName to src in .aspx
Thanks,
Ahmed.
*********** U P D A T E ***********
This is Code-Behind and my goal is to open .pdf file in a frame so that I can open together with another .htm page in one window:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sFilePath As String
Dim buffer As Byte()
Using con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings()("SqlServerConnection").ConnectionString
con.Open()
Using cmd As New SqlCommand("SELECT imageLaw FROM Laws WHERE ID = #ID", con)
Dim pID As New SqlParameter("#ID", SqlDbType.Int)
pID.Value = CType(Request.QueryString("pID"), Integer)
cmd.Parameters.Add(pID)
buffer = cmd.ExecuteScalar()
End Using
con.Close()
End Using
sFilePath = System.IO.Path.GetTempFileName()
System.IO.File.Move(sFilePath, System.IO.Path.ChangeExtension(sFilePath, ".pdf"))
sFilePath = System.IO.Path.ChangeExtension(sFilePath, ".pdf")
System.IO.File.WriteAllBytes(sFilePath, buffer)
'Literal1.Text = "<frame src=\"" + sFilePath + " \ ">"
'TextBox1.Text = sFilePath
' ''Response.WriteFile(sFilePath)
' ''Response.End()
' ''Response.BinaryWrite(buffer)
'Dim act As Action(Of String) = New Action(Of String)(AddressOf OpenFilePW)
'act.BeginInvoke(sFilePath, Nothing, Nothing)
End Sub
Private Shared Sub OpenFilePW(ByVal sFilePath As String)
Using p As New System.Diagnostics.Process
p.StartInfo = New System.Diagnostics.ProcessStartInfo(sFilePath)
p.Start()
p.WaitForExit()
Try
System.IO.File.Delete(sFilePath)
Catch
End Try
End Using
End Sub
I'm remarking last rows because I don't want .pdf file to be opened outside the web page.
You may use a asp:Literal as container for your frame's HTML, or use the <%= Variable %> tag...
Solution 1 :
<frameset cols="100%,*">
<asp:Literal ID="litFrame" runat="server"></asp:Literal>
</frameset>
and in CB : litFrame.Text = "<frame name=\"main\" target=\"main\" src=\"" + FilePathName + "\">";
Solution 2 :
In ASPX :
<frameset cols="100%,*">
<frame name="main" target="main" src="<%= myTarget %>">";
</frameset>
PS : frames are deprecated in web since more than 10 years...

Regarding itemdatabound in repeater

I have following code in page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
GetDetails()
PopulateRepeater()
End If
End Sub
Sub PopulateRepeater()
Dim dt As DataTable = GetDetails()
Dim dtDoc As DataTable = objdoc.GetDocDetails(Session("RegID"))
If dtDoc.Rows.Count > 0 Then
Dim strUserName As String = dt.Rows(0)("Name")
Dim files As IList(Of FileInfo) = New List(Of FileInfo)()
Dim filters As String = "*.jpg;*.png;*.gif"
For Each filter As String In filters.Split(";"c)
Dim fit As FileInfo() = New DirectoryInfo(Me.Server.MapPath("../SiteImages/" & strUserName & "/" & Session("RegID") & "/")).GetFiles(filter)
For Each fi As FileInfo In fit
files.Add(fi)
Next
Next
strPath = Server.MapPath("../SiteImages/" & strUserName & "/" & Session("RegID") & "/")
Me.Repeater1.DataSource = files
Me.Repeater1.DataBind()
End If
End Sub
I have following code in itemdatabound
Dim ThViewr As Bright.WebControls.ThumbViewer = DirectCast(e.Item.FindControl("Th1"), Bright.WebControls.ThumbViewer)
Dim dtUser As DataTable = GetDetails()
Dim dtDoc As DataTable = objdoc.GetDocDetails(Session("RegID"))
Dim strUserName As String = dtUser.Rows(0)("Name")
If dtDoc.Rows.Count > 0 Then
For i As Integer = 0 To dtDoc.Rows.Count - 1
Dim ImagePath As String = "../SiteImages/" & strUserName & "/" & Session("RegID") & "/" + dtDoc.Rows(i)("ImageName")
ThViewr.ImageUrl = ImagePath
Next
End If
My aspx contains
<div style="clear:both;">
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<span style="padding:2px 10px 2px 10px">
<bri:ThumbViewer Id="Th1" runat="server" Height="100px" Width="100px"/>
</span>
</ItemTemplate>
</asp:Repeater>
</div>
If the imagePath ="../SiteImages/Ram/PR/First.jpg" Means the folder PR aontains exactly 3 images namely First.jpg,Second.jpg and Third.jpg.
Now with above code three images are coming but Third.jpg is repeating 3 times.First.jpg and Second.jpg is not coming.Can anybody help to resolve this.
The ItemDataBound event is raised once for every object in the bound list, so it will be fired three times in your case; once for each file. You should not loop over your data table, but rather grab the current item from the event args.
Update: looking closer at the code I find it somewhat confusing. You bind a list of FileInfo objects to the repeater, but fetch data from a DataTable when the items are bound. I am guessing that you want to show the files found, and I think that the following code in ItemDataBound will do that for you:
Dim ThViewr As Bright.WebControls.ThumbViewer = DirectCast(e.Item.FindControl("Th1"), Bright.WebControls.ThumbViewer)
Dim dtUser As DataTable = GetDetails()
Dim strUserName As String = dtUser.Rows(0)("Name")
Dim ImagePath As String = "../SiteImages/" & strUserName & "/" & Session("RegID") & "/" + DirectCast(e.Item.DataItem, FileInfo).Name
ThViewr.ImageUrl = ImagePath

Resources