Upload image, display and allow to upload next image - asp.net

I have this event written in asp.net(VS2012). I want the user to upload an image and description, after upload I want to display the image name and description in grid view on the page and allow to upload next image. I am not sure why the event gets called twice and the second time I get "Object reference not set to...." error at "if strfile.hasfile...". Hope I explained it correctly.
Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
Dim strfilename, strfilepath As String
strfilename = Nothing
strfilepath = lblInciID.Text.Trim
Try
' Dim CurrentPath As String = Server.MapPath("C:\DSimages\")
If strFile.HasFile Then
Try
strFile.SaveAs("C:\DSimages\" & _
strfilepath + strFile.FileName)
'Save the name in the table
strfilename = strFile.PostedFile.FileName
strfilename = strfilepath + strfilename
If strFile.HasFile Then strFile = Nothing
Catch ex As Exception
MsgBox("ERROR: " & ex.Message.ToString())
End Try
End If
ImageDS.InsertParameters("ImagePath").DefaultValue = strfilename.Trim
ImageDS.InsertParameters("ImageDescription").DefaultValue = txtPicDesc.Text.Trim()
ImageDS.InsertParameters("InciID").DefaultValue = lblInciID.Text.Trim()
ImageDS.InsertParameters("Category").DefaultValue = lblCategory.Text.Trim()
ImageDS.Insert()
'MsgBox("Picure was uploaded successfully! Upload another picture or click on 'Cancel'")
txtPicDesc.Text = ""
Catch ex As Exception
MsgBox(ex.Message)
End Try
GridView_Image.Visible = True
End Sub
aspx page:
<div class="clearclass padtop">
<div class="div2">
<h4 style="width:23.2em">Browse file</h4>
<asp:FileUpload runat="server" ID="strFile" width="25em" Height="30px"/><br />
<asp:Label runat="server" ID="imgtoupload"></asp:Label>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorFile" runat="server" ErrorMessage="File" ControlToValidate="strFile"
CssClass="fontred style_bold" Display="Static">File</asp:RequiredFieldValidator>
</div>
<div class="div2">
<h4 style="width:24.6em">Add Description</h4>
<asp:TextBox runat="server" ID="txtPicDesc" Width="30.4em" Height="5em" TextMode="MultiLine"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorDesc" runat="server" ControlToValidate="txtPicDesc" CssClass="fontred style_bold"
ErrorMessage="Description">Description</asp:RequiredFieldValidator>
</div>
</div>
<asp:GridView ID="GridView_Image" runat="server" DataSourceID="ImageDS" AutoGenerateColumns="False" HorizontalAlign="Center" Visible="false">
<Columns>
<asp:BoundField DataField="InciID" HeaderText="InciID" SortExpression="InciID" />
<asp:BoundField DataField="Imagepath" HeaderText="Imagepath" SortExpression="Imagepath" />
<asp:BoundField DataField="ImageDescription" HeaderText="ImageDescription" SortExpression="ImageDescription" />
</Columns>
<RowStyle BackColor="#EFF3FB" Height="2em" />
</asp:GridView>

Related

issues with firing a link button click event within a gridview in a vb asp.net web application

I have web application created with VB Visual Studio 2008. I have a created a new page to display a grid view showing contracts from a database with a certain status. In the grid view i have an item template field with a link button. The default text for the link button is Add.
When the button is clicked, i would like to add the id number of the contract from the db to a list of integers. If the contract id is present on the list, the text of the button should read as 'Remove' and it should then be removed from the list. if it is not present in the list, the text of the button should read as 'add' and it should be added to the list. In the click event for the button, i have the code to achieve this.
The page loads fine and displays the items in the grid view, however when i click the add button it was generating a null exception error pointing to my casting the link button. I then put the grid view in an update panel, and i no longer get the null exception error but now nothing happens.
here is aspx code & vb code for the grid view. the null error was firing on the line with Dim btnT As New LinkButton and the next line with btnT = CType(sender, LinkButton). Any assistance will be greatly appreciated, the strange thing is have very similar code (i practically duplicated the code) in a vb asp.net web site, and it works fine.
<td align="center">
<div class="style82">
Contract Queue
</div>
<hr />
<div class = "queue">
<div class="status">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</div>
<div>
<asp:UpdatePanel ID="MainUpdate" runat="server">
<ContentTemplate>
<div>
<asp:GridView ID="grdvContract" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" BackColor="White"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"
Font-Names="Arial" Font-Size="Small"
ForeColor="Black" GridLines="Vertical" PageSize="25" Width="100%"
OnRowDataBound="grdvContract_RowDataBound">
<FooterStyle BackColor="#333300" BorderColor="#FF5050" BorderStyle="Solid"
ForeColor="#FF9900" />
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:BoundField DataField="dealno" HeaderText="Deal No" SortExpression="dealno" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Currency" HeaderText="Currency"
SortExpression="Currency" />
<asp:BoundField DataField="Amount" HeaderText="Amount"
DataFormatString="{0:#,###,###.00}" SortExpression="Amount" HtmlEncode="false" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
<asp:HyperLinkField DataNavigateUrlFields="dealno" Text='<img src="graphics/txt.gif" border="0" />'
DataNavigateUrlFormatString="deal_ticket_standard.aspx?id={0}"
HeaderStyle-HorizontalAlign="Left"
HeaderText="Standard View" ItemStyle-HorizontalAlign="Left" Target="javascript:window.open ('deal_ticket_standard.aspx?id={0}', 'win', 'height=400,width=400,location=no,menubar=no,resizable,scrollbars,status=no,toolbar=no');">
<HeaderStyle Width="50" />
<ItemStyle HorizontalAlign="Left"/>
</asp:HyperLinkField>
<asp:BoundField DataField="rate" HeaderText="Rate" ReadOnly="True" SortExpression="rate"/>
<asp:BoundField DataField="cDate" HeaderText="Contract Date" ReadOnly="True" SortExpression="cDate" />
<asp:TemplateField HeaderText = "Action" >
<ItemTemplate>
<asp:LinkButton ID="btnAction" runat="server" Text = "Add" AutoPostBack = "False"
OnClick = "btnAction_Click" CausesValidation="False"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
<div id="ActionStatus" runat="server" visible="false" class="status">
** <asp:Literal ID="ltActionSuccess" runat="server"></asp:Literal> **
</div>
<div>
<br />
Total Deals to be included in this file: <asp:Label ID="lblTotal" class="total" runat="server"></asp:Label>
<br />
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="MainUpdateProgress" runat="server" AssociatedUpdatePanelID="MainUpdate">
<ProgressTemplate>
<div >
Please wait, loading updated content...
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</div>
</td>...
Imports System.Data
Partial Public Class contract_queue
Inherits System.Web.UI.Page
Private _DealList As List(Of Integer)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
DealList = New List(Of Integer)
FillContractQueue()
End If
End Sub
Public Property DealList() As List(Of Integer)
Get
Return _DealList
End Get
Set(ByVal value As List(Of Integer))
_DealList = value
End Set
End Property
Protected Sub grdvContract_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdvContract.RowDataBound
Dim grid_row As GridViewRow
grid_row = e.Row
If e.Row.RowType = DataControlRowType.DataRow Then
Dim deal_no As Integer = CInt(DataBinder.Eval(grid_row.DataItem, "dealno"))
Dim btnR As LinkButton = grid_row.FindControl("btnAction")
btnR.Attributes.Add("dealid", deal_no)
'If DealList.Contains(dealno) Then
' btnR.Text = "Remove"
'Else
' btnR.Text = "Add"
'End If
End If
End Sub
Protected Sub btnAction_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Me.ActionStatus.Visible = True
Me.ltActionSuccess.Text = "Test"
Dim total As Integer = 0
total = DealList.Count
Me.lblTotal.Text = total
Dim btnT As New LinkButton
btnT = CType(sender, LinkButton)
Dim deal_id As Integer = btnT.Attributes("dealid")
If DealList.Contains(deal_id) Then
DealList.Remove(deal_id)
btnT.Text = "Add"
total = DealList.Count
Me.ltActionSuccess.Text = "Deal " & deal_id & " added to file"
Me.lblTotal.Text = total
Else
DealList.Add(deal_id)
total = DealList.Count
btnT.Text = "Remove"
Me.ltActionSuccess.Text = "Deal " & deal_id & " removed from file"
Me.lblTotal.Text = total
End If
End Sub
Protected Sub FillContractQueue()
Dim ContractDeals As New DataSet()
'set up db connection'
Dim strConnect As String = ConfigurationManager.ConnectionStrings("ibl_treasuryConnectionString").ConnectionString
Dim objConnection As New System.Data.SqlClient.SqlConnection(strConnect)
Dim strQuery As String
strQuery = "SELECT convert(varchar, t_deal_register.contractdate, 106) AS cDate, t_deal_register.id AS dealno, t_deal_type.dealtype AS Type, t_client.client_name AS Client, t_dealer_ibl.dealer_ibl + '/' + t_dealer_client.dealer_client AS Dealers, t_deal_register.amount AS Amount, t_deal_register.fxrate AS rate, t_status.Status, t_currency.currency + '/' + t_currency_1.currency AS Currency FROM t_deal_register INNER JOIN t_deal_type ON t_deal_register.dealtype = t_deal_type.id INNER JOIN t_client ON t_deal_register.clientname = t_client.id INNER JOIN t_dealer_ibl ON t_deal_register.dealer_ibl = t_dealer_ibl.id INNER JOIN t_dealer_client ON t_deal_register.dealer_client = t_dealer_client.id INNER JOIN t_currency ON t_deal_register.currency = t_currency.id INNER JOIN t_status ON t_deal_register.status = t_status.id INNER JOIN t_currency AS t_currency_1 ON t_deal_register.pay_currency = t_currency_1.id where t_deal_register.status = '14' ORDER BY t_deal_register.id DESC"
Dim objCommand As New System.Data.SqlClient.SqlCommand(strQuery, objConnection)
objConnection.Open()
Try
Dim DealAdapter As New System.Data.SqlClient.SqlDataAdapter(objCommand)
DealAdapter.Fill(ContractDeals)
Catch ex As Exception
Me.lblMessage.Text = ex.Message
Finally
objConnection.Close()
If ContractDeals.Tables.Count > 0 Then
grdvContract.DataSource = ContractDeals
grdvContract.DataBind()
End If
End Try
End Sub
End Class
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkButtonID" runat="server"
OnClick="lnkButton_Click" Text='<%#DataBinder.GetPropertyValue(Container.DataItem, "ID")%>'
name = '<%#DataBinder.GetPropertyValue(Container.DataItem, "Name")%>'
address = '<%#DataBinder.GetPropertyValue(Container.DataItem, "address")%>'
description = '<%#DataBinder.GetPropertyValue(Container.DataItem, "Description")%>'
></asp:LinkButton>
</ItemTemplate>

How to enable and disable buttons in a gridview in asp.net

I currently have a GridView with two buttons that I have added using the following code;
<asp:GridView ID="gvResults" AutoGenerateColumns="False" runat="server" Font-Size="small"
DataKeyNames="BeachHutID" OnRowDataBound="gvResults_RowDataBound" CssClass="BBCSearch">
<Columns>
<asp:BoundField DataField="BeachHutID" SortExpression="BeachHutID" Visible="false">
</asp:BoundField>
<asp:ImageField DataImageUrlField="HutImage" ItemStyle-Width="1%" ReadOnly="true" />
<asp:BoundField HeaderText="Facilities" DataField="Facilities" Visible="false"></asp:BoundField>
<asp:BoundField HeaderText="Info" DataField="Info" Visible="false"></asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="lblHolder" runat="server"></asp:PlaceHolder>
<br />
<asp:PlaceHolder ID="imgHolder" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnHire" CommandArgument='<%# Eval("BeachHutID") %>' runat="server"
Text="Hire Beach Hut" OnClick="Hire_Click" />
<asp:Button ID="ButtonLogin" CommandArgument='<%# Eval("BeachHutID") %>' runat="server"
Text="Login to Hire Beach Hut" OnClick="Login_Redirect" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
What I want to happen is if the user is logged in, the btnHire button should be enabled and showing and if they're not logged in, ButtonLoggedIn is showing and btnHire is hidden. This is the code I have at the moment;
Public Sub PopulateGrid()
Dim AvailableHuts As New DataTable
AvailableHuts = GetData()
gvResults.DataSource = AvailableHuts
gvResults.DataBind()
gvResults.Enabled = True
'If statement controlling the enabling and disabling of the Beach Hut booking button
If Session("LoginID") = "" Then
For Each rowItem As GridViewRow In gvResults.Rows
rowItem.Cells(5).Enabled = True
Next
End If
lblCaption.Text = "Your search returned " + CStr(AvailableHuts.Rows.Count) + " results"
End Sub
At the moment both buttons are enabled at all times and I'm not sure what I need to add/changed to get the desired result.
From the answer posted by #Andrei, I have added the following to to this Sub;
Protected Sub gvResults_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles gvResults.RowDataBound
Dim URL(), Text() As String
Dim img As Image
Dim lbl As Label
Dim FacilitiesImg As PlaceHolder = e.Row.FindControl("imgHolder")
Dim Infolbl As PlaceHolder = e.Row.FindControl("lblHolder")
'Added Code from answer
Dim hireBtn As Button = CType(e.Row.FindControl("btnHire"), Button)
hireBtn.Visible = Not String.IsNullOrEmpty(Session("LoginID"))
'Added Code from answer
Dim LoginBtn As Button = CType(e.Row.FindControl("ButtonLogin"), Button)
LoginBtn.Visible = String.IsNullOrEmpty(Session("LoginID"))
If e.Row.RowType = DataControlRowType.DataRow Then
URL = e.Row.DataItem(3).Split(",")
Text = e.Row.DataItem(2).Split(",")
'Add the Facilities Images to the grid Row
For Each item In URL
If item.ToString <> "" Then
img = New Image
img.ImageUrl = item.ToString
FacilitiesImg.Controls.Add(img)
End If
Next
'Add the information to the grid row
'convert # into a carriage return and * into £
For Each item In Text
If item.ToString <> "" Then
lbl = New Label
lbl.Text = Replace(Replace(item.ToString, "#", "<br />"), "*", "£")
Infolbl.Controls.Add(lbl)
End If
Next
End If
End Sub
However I'm receiving the following error when trying to run the program;
Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class
Any assistance would be much appreciated.
Thanks
Not sure how is your authentication implemented, but let's assume you use HttpContext.Current.Request.IsAuthenticated. Then you can just manipulate Visible property of the buttons in code behind:
btnHire.Visible = HttpContext.Current.Request.IsAuthenticated
ButtonLoggedIn.Visible = Not HttpContext.Current.Request.IsAuthenticated
Update.
Sorry, somehow missed from the post the fact that you seems to be using Session("LoginID") to decide if the use is logged in. The you can do this:
btnHire.Visible = Not String.IsNullOrEmpty(Session("LoginID"))
ButtonLoggedIn.Visible = String.IsNullOrEmpty(Session("LoginID"))
Update 2.
As it turns out, buttons are a part of GridView row. As they are inside the template, you cannot really reach them in the code behind. So you can take two options.
First, you can subscribe to RowDataBound event (which you already did), and inside it do FindControl in the current row to find the necessary button:
Sub gvResults_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
...
Button hireBtn = CType(e.Row.FindControl("btnHire"), Button);
hireBtn.Visible = Not String.IsNullOrEmpty(Session("LoginID"))
and likewise for the second button.
Second, you can try doing it in the markup:
<asp:Button ID="btnHire" CommandArgument='<%# Eval("BeachHutID") %>'
runat="server" Text="Hire Beach Hut" OnClick="Hire_Click"
Visible=<%# String.IsNullOrEmpty(Session("LoginID")) %> />
try
<asp:Button ID="btnHire" CommandArgument='<%# Eval("BeachHutID") %>' runat="server" Visible='<%# islogin()?true:false %>' Text="Hire Beach Hut" OnClick="Hire_Click" />
<asp:Button ID="ButtonLoggedIn" CommandArgument='<%# Eval("BeachHutID") %>' runat="server" Visible='<%# islogin()?false:true %>' Text="Login to Hire Beach Hut" OnClick="Login_Redirect" />
paste this code to aspx.cs page:
Public Shared Function isLogin() As Boolean
Dim stat As Boolean = False
Try
If Session("LoginID") IsNot Nothing AndAlso Session("LoginID") <> "" Then
stat = True
End If
Catch e1 As Exception
stat = False
End Try
Return stat
End Function
Edit2:
Visible='<%# islogin()?false:true %> this means if isLogin() return true then Visible property set to false else it's visible property set to true.

Gridview not sorting

I've come across this strange error and it's been bugging me for hours now.
I've got some LinkButtons on my screen and depending on which button the user chooses a label's text is set, a GridView is displayed and the Datasource of this GridView is assigned based on the text of the label.
This all works fine and dandy. However the problem arises when I want to sort this GridView.
At the moment, nothing happens. When I attempt to sort a column the page just refreshes and I'm left with the same unsorted mess in my GridView.
I've put my application into debug mode with breakpoints along the way and noticed that when I get to this step (the full code can be seen at the bottom of this post) :
senderGridView.SortExpression = button.CommandArgument
the senderGridView.SortExpression is "" so for some reason it's not passing the sort expression.
Hopefully somebody can enlighten me as to why my grid isn't sorting as I'm sure it's just a stupid mistake somewhere but any help would be appreciated, thanks.
Code that you may require...
My sub that sets the sort images when a row is created can be seen below:
Protected Sub GridViewSortImages(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim senderGridView As GridView = CType(sender, GridView)
'Loop through each cell in header row
For Each cell As TableCell In e.Row.Cells
If cell.HasControls Then
Dim button As LinkButton = TryCast((cell.Controls(0)), LinkButton)
Dim gv As New HtmlGenericControl("div")
Dim lnkName As New Label()
'Test cell to see if a link button exists (i.e. Allow Sorting = True)
If Not (button Is Nothing) Then
'Create new label and image and set to standard unsorted view
lnkName.Text = button.Text
Dim image As New System.Web.UI.WebControls.Image
image.ImageUrl = "images/sort-1x1.png"
image.ToolTip = "Sort"
image.AlternateText = "Sort"
'Test to see if grid is already sorted, and apply relevant image & tooltip
If senderGridView.SortExpression = button.CommandArgument Then
If senderGridView.SortDirection = SortDirection.Ascending Then
image.ImageUrl = "images/sort-asc.png"
image.ToolTip = "Sort Descending"
image.AlternateText = "Sort Descending"
Else
image.ImageUrl = "images/sort-desc.png"
image.ToolTip = "Sort Ascending"
image.AlternateText = "Sort Ascending"
End If
End If
'Add label and image to new div
gv.Controls.Add(lnkName)
gv.Controls.Add(image)
'Replace original column header with new div
button.Controls.Add(gv)
End If
End If
Next
End Sub
My RowCreated sub for the GridView...
Protected Sub grvHomeRisk_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles grvHomeRisk.RowCreated
If Not (e.Row Is Nothing) AndAlso e.Row.RowType = DataControlRowType.Header Then
GridViewSortImages(sender, e) 'Call sort code
End If
End Sub
My Sorting sub...
Protected Sub grvHomeRisk_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grvHomeRisk.Sorting
Select Case lblBreachHeaderb.Text
Case "Current Risks"
grvHomeRisk.DataSource = SQLDS_ListCurrentRisk
Case "All Risks Overdue"
grvHomeRisk.DataSource = SQLDS_ListAllRiskOverdue
Case "My Risks"
grvHomeRisk.DataSource = SQLDS_ListMyRisk
Case "My Risks Overdue"
grvHomeRisk.DataSource = SQLDS_ListRiskOverdue
Case "Risks Requested to Score & Re-Score"
grvHomeRisk.DataSource = SQLDS_ListScores
Case "Risks Requested to Score"
grvHomeRisk.DataSource = SQLDS_ListRiskScores
Case "Risks Requested to Re-Score"
grvHomeRisk.DataSource = SQLDS_ListRiskReScores
End Select
grvHomeRisk.DataBind()
End Sub
My GridView...
<asp:GridView ID="grvHomeRisk" runat="server" AutoGenerateColumns="false" AllowSorting="true"
CssClass="GridMain" UseAccessibleHeader="false"
ForeColor="#333333" GridLines="None" Width="780px" BorderWidth="0px"
AllowPaging="true" PageSize="5" CellPadding="3" DataKeyNames="IDRISK">
<Columns>
<asp:CommandField ButtonType="Image" SelectText="View Risk" ShowSelectButton="True" SelectImageUrl="~/Images/button-select1.png" />
<asp:BoundField DataField="TXRISKSUMMARY" HeaderText="Risk" ReadOnly="True" />
<asp:BoundField DataField="TSRISKSTART" HeaderText="Start Date" ReadOnly="True" DataFormatString="{0:dd MMM yyyy}" />
<asp:BoundField DataField="TSRISKREVIEW" HeaderText="Review Date" SortExpression="TSRISKREVIEW" ReadOnly="True" DataFormatString="{0:dd MMM yyyy}" />
<asp:BoundField DataField="TXUSER_NAME_O" HeaderText="Owner" SortExpression="TXUSER_NAME_O" ReadOnly="True" />
<asp:BoundField DataField="TXDESCRIPTION" HeaderText="Risk Element" SortExpression="TXDESCRIPTION" ReadOnly="True" />
<asp:BoundField DataField="TSDATMOD" HeaderText="Date Modified" ReadOnly="True" DataFormatString="{0:dd MMM yyyy}" />
<asp:BoundField DataField="TXUSER_NAME_M" HeaderText="Modified By" ReadOnly="True" />
</Columns>
<PagerTemplate>
<table>
<tr>
<td>
<asp:Button ID="FirstButton" runat="server" CommandArgument="First" CommandName="Page" Text="<<" CssClass="buttongrid" ToolTip="First" OnClientClick="needToConfirm = false;" />
<asp:Button ID="PrevButton" runat="server" CommandArgument="Prev" CommandName="Page" Text="Previous" CssClass="button" ToolTip="Previous" OnClientClick="needToConfirm = false;" />
</td>
<td>
<asp:Label ID="lblPageCount" runat="server" CssClass="TextA12Bold" Visible="false"></asp:Label>
</td>
<td>
<asp:Button ID="NextButton" runat="server" CommandArgument="Next" CommandName="Page" Text="Next" CssClass="button" ToolTip="Next" OnClientClick="needToConfirm = false;" />
<asp:Button ID="LastButton" runat="server" CommandArgument="Last" CommandName="Page" Text=">>" CssClass="buttongrid" ToolTip="Last" OnClientClick="needToConfirm = false;" />
</td>
</tr>
</table>
</PagerTemplate>
</asp:GridView>

asp.net file upload (how to create a hyperlink to uploaded documents, displayed in my gridview)

Afternoon All,
I have a simple file upload tutorial that i have completed for a site that i am developing in visual studio 2010.
I just want to enhance the gridview that shows the uploaded file by making the file a link to that document in the gridview. This will enable users to then upload the file and view the file by pressing a link in the gridview to view the file.
Here is my code so far...
<form id="form1" runat="server">
<div>
<table style="width: 90%">
<tr>
<td style="width: 100px"> Single File Upload:<br />
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Button ID="buttonUpload" runat="server" Text="Upload" /><br />
<br />
<asp:GridView ID="UploadedFiles" DataSource="<%# GetUploadList() %>" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
And here is the .VB page
Partial Class test
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
UploadedFiles.DataBind()
End If
End Sub
Protected Function GetUploadList() As String()
Dim folder As String = Server.MapPath("~/Uploads")
Dim files() As String = Directory.GetFiles(folder)
Dim fileNames(files.Length - 1) As String
Array.Sort(files)
For i As Integer = 0 To files.Length - 1
fileNames(i) = Path.GetFileName(files(i))
Next
Return fileNames
End Function
Protected Sub UploadThisFile(ByVal upload As FileUpload)
If upload.HasFile Then
Dim theFileName As String = Path.Combine(Server.MapPath("~/Uploads"), upload.FileName)
If File.Exists(theFileName) Then
File.Delete(theFileName)
End If
upload.SaveAs(theFileName)
End If
End Sub
Protected Sub buttonUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonUpload.Click
UploadThisFile(FileUpload1)
UploadedFiles.DataBind()
End Sub
End Class
Im not too sure on how to add a little extra code into the Protected Sub UploadThisFile(ByVal upload As FileUpload) section.
Any help to make this static list of items that are available in the Uploads file to a list that holds a link to these individual documents is much appriechiated.
Many thanks in advance,
Betty
Tweat your code this way:
Generate the tags:
Protected Function GetUploadList() As String()
Dim folder As String = Server.MapPath("~/Uploads")
Dim files() As String = Directory.GetFiles(folder)
Dim fileNames(files.Length - 1) As String
Dim lnk As String = String.Empty
Array.Sort(files)
For i As Integer = 0 To files.Length - 1
lnk = " File"
fileNames(i) = Path.GetFileName(files(i)) & lnk
lnk = ""
Next
Return fileNames
End Function
Access each gridview cell to decode the markup:
Protected Sub UploadedFiles_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles UploadedFiles.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim tcls As TableCellCollection = e.Row.Cells
For Each tc As TableCell In tcls
tc.Text = Server.HtmlDecode(tc.Text)
Next
End If
End Sub
If you want the "<a>" tag to get generated on your file name you could change each filename this way:
fileNames(i) = "" & Path.GetFileName(files(i)) & ""
Hope it helps.

How to access vb.net button click event on modal popup button click event?

my source code in design part is:
<asp:Panel ID="Panel1" runat="server" Style="display: none" CssClass="modalPopup">
<asp:Panel ID="Panel3" runat="server" Style="cursor: move;background-color:#DDDDDD;border:solid 1px Gray;color:Black">
<div>
<p>Would you like to book the seat?</p>
</div>
</asp:Panel>
<div>
<p style="text-align: center;">
<asp:Button ID="OkButton" runat="server" Text="OK" OnClick="OkButton_Click" />
<asp:Button ID="CancelButton" runat="server" Text="Cancel" />
</p>
</div>
</asp:Panel>
I want to access OkButton_Click in vb.net
The code is as follows:
Protected Sub OkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OkButton.Click
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0 ;data source=" & Server.MapPath(".\App_Data\IFFI.mdb") & ";")
Dim Cmd As OleDbCommand
Dim Qry As String
con.Open()
Qry = "update seat_layout set lock_status=1,booked_status=1 where theatre_id='" + ddl_theatre.SelectedValue.ToString() + "' and seat_id='" + Session("seat_id").ToString() + "'"
Dim img As Button
img.BackColor = Drawing.Color.Purple
img.Enabled = False
Cmd = New OleDbCommand(Qry, con)
Cmd.ExecuteNonQuery()
con.Close()
End Sub
Ok button click is not accessing click event.
Try changing the sub to "public" instead of "protected".
(I apologize if this question was too old for me to answer it now).

Resources