end of statement expected - asp.net

Imports System
Imports System.IO
Imports System.Linq
Namespace PhotoGalleryApp
Partial Public Class Index
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Path to photos folder
Dim photosRelativePath = "~/photos/"
Dim photosFilePath = Me.Server.MapPath(photosRelativePath)
' Get list of img files from photos folder
Dim photos = From file In New DirectoryInf(photosFilePath).GetFiles()
Where (file.Name.EndsWith(".jpg",
StringComparison.InvariantCultureIgnoreCase)
OrElse file.Name.EndsWith(".gif",
StringComparison.InvariantCultureIgnoreCase)
OrElse file.Name.EndsWith(".png",
StringComparison.InvariantCultureIgnoreCase))
Select photosRelativePath & file.Name
' Return photos as string array
lstPhotos.DataSource = photos.ToArray()
lstPhotos.DataBind()
End Sub
End Class
End Namespace
I am using this code for jQuery Cycle Plugin.
This is the aspx code
<asp:ListView ID="lstPhotos" runat="server">
<ItemTemplate>
<img src='<%# ResolveUrl(Container.DataItem.ToString()) %>' width="250" height="300" />
</ItemTemplate>
</asp:ListView>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.cycle/2.88/jquery.cycle.all.js"></script>
<script type="text/javascript">
$("#photos").cycle("toss");
</script>
I am setting the DataSource of the LIstView as Photos.ToArray() in the code behind..but still i get the error.. "Select DataSource for ListView"

Try replacing
Dim photos = From file In New DirectoryInfo(photosFilePath).GetFiles()
Where (file.Name.EndsWith(".jpg",
StringComparison.InvariantCultureIgnoreCase)
OrElse
file.Name.EndsWith(".gif",
StringComparison.InvariantCultureIgnoreCase) OrElse
file.Name.EndsWith(".png",
StringComparison.InvariantCultureIgnoreCase))
photosRelativePath & file.Name
with
Dim photos = From file In New DirectoryInfo(photosFilePath).GetFiles()
Where (file.Name.EndsWith(".jpg",
StringComparison.InvariantCultureIgnoreCase) OrElse
file.Name.EndsWith(".gif",
StringComparison.InvariantCultureIgnoreCase) OrElse
file.Name.EndsWith(".png",
StringComparison.InvariantCultureIgnoreCase))
select photosRelativePath & file.Name

Related

Create Chart using Fusionchart and get data from database in VB.NET

I want to create a bar chart using fusionchart, and get the data from database
This is my UI, if I click this link will go to the chart page
FRONT CODE FOR UI PAGE (Statistics.aspx)
<form id="form_statistics" runat="server">
<div>
<label for="name"></label>
<asp:DropDownList ID="ddlGender" runat="server"></asp:DropDownList>
<asp:Button ID="BtnSearch" runat="server" Text="Search" />
<br/><br/>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
<asp:Repeater ID="repGender" runat="server">
<HeaderTemplate>
<table cellspacing="0" rules="all" border="1">
<tr>
<th>Gender</th>
<th>Total</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("GENDER")%>
</td>
<td style="text-align: center">
<a href='<%# "Chart.aspx?GENDER_ID=" & Eval("GENDER") & ""%>'> <%# Eval("TOTAL")%></a>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr style="font-weight: bold">
<td>Grand Total</td>
<td style="text-align: center">
<asp:Label runat="server" ID="lblTotal"></asp:Label>
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
BEHIND CODE Statistics.aspx
Imports System.Data.SqlClient
Imports System.IO
Imports WebUserCtrl
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports FusionCharts.Charts
Imports System.Reflection
Partial Class Statistics
Inherits App.Main
Dim MyTotal As Integer
Dim MethodBase As Object
Private Property Label As Object
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindData()
ddlGender_Bind()
End If
End Sub
Sub BindData()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
dal.DB.Parameters.Clear()
dal.DB.AddParameter("#GENDER", ddlGender.SelectedValue)
If dal.DB.ExecuteProcedure(dt, "GENDER_BB") Then
repGender.DataSource = dt
repGender.DataBind()
End If
End Sub
Protected Sub repGender_ItemCommand(source As Object, e As RepeaterCommandEventArgs) Handles repGender.ItemCommand
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
End Sub
Protected Sub repGender_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles repGender.ItemDataBound
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
Dim gData As DataRowView = e.Item.DataItem
MyTotal = MyTotal + gData.Item("TOTAL")
End If
If e.Item.ItemType = ListItemType.Footer Then
' set the total value in footer
Dim lblTotal As Label = e.Item.FindControl("lblTotal")
lblTotal.Text = MyTotal
End If
End Sub
Public Sub ddlGender_Bind()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
If dal.DB.ExecuteProcedure(dt, "GENDER_R") Then
Share.LoadList(ddlGender, "GENDER", "GENDER_ID", dt, Enums.MsgCode.PleaseSelect.ToString, ListOrder.ByValue)
End If
End Sub
Protected Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
dal.DB.Parameters.Clear()
dal.DB.AddParameter("#GENDER", ddlGender.SelectedValue)
If dal.DB.ExecuteProcedure(dt, "GENDER_B") Then
repGender.DataSource = dt
repGender.DataBind()
End If
End Sub
End Class
FRONT CODE FOR Chart.aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Chart.aspx.vb" Inherits="Chart" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<!-- Include jQuery -->
<script type="text/javascript" src=" https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!-- Include fusioncharts core library file -->
<script type="text/javascript" src=" https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
<!-- Include fusion theme file -->
<script type="text/javascript" src=" https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
<!-- Include fusioncharts jquery plugin -->
<script type="text/javascript" src=" https://rawgit.com/fusioncharts/fusioncharts-jquery-plugin/develop/dist/fusioncharts.jqueryplugin.min.js"></script>
<title>Chart</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
BEHIND CODE Chart.aspx
Imports System.Data.SqlClient
Imports System.IO
Imports WebUserCtrl
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports FusionCharts.Charts
Imports System.Reflection
Partial Class Chart
Inherits App.Main
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
If Not IsPostBack Then
CreateChart()
End If
End Sub
Sub CreateChart()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
Dim jsonData As New StringBuilder()
Dim ReqComma As Boolean = False
jsonData.Append("{'chart': {")
jsonData.Append("'caption': 'Chart',")
jsonData.Append("'yAxisName': 'Number',")
jsonData.Append("'theme': 'fusion'")
jsonData.Append("},")
jsonData.Append("'data' : [")
For Each dr As DataRow In dt.Rows
If ReqComma Then
jsonData.Append(",")
Else
ReqComma = True
End If
jsonData.Append("{" + "'label': '" & Replace(dr("GENDER"), "'", "\'") & "', 'value': '" & dr("TOTAL") & "'" + "}")
Next
jsonData.Append("]")
jsonData.Append("}")
Dim ChartOutput As New FusionCharts.Charts.Chart("column2d", MethodBase.GetCurrentMethod().Name, "100%", "300", "json", jsonData.ToString())
Literal1.Text = ChartOutput.Render()
End Sub
End Class
I can go to the other page(Chart.aspx) but I did not get the output, the data is not display. I am not sure where should I put the
Sub CreateChart()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
Dim jsonData As New StringBuilder()
Dim ReqComma As Boolean = False
jsonData.Append("{'chart': {")
jsonData.Append("'caption': 'Chart',")
jsonData.Append("'yAxisName': 'Number',")
jsonData.Append("'theme': 'fusion'")
jsonData.Append("},")
jsonData.Append("'data' : [")
For Each dr As DataRow In dt.Rows
If ReqComma Then
jsonData.Append(",")
Else
ReqComma = True
End If
jsonData.Append("{" + "'label': '" & Replace(dr("GENDER"), "'", "\'") & "', 'value': '" & dr("TOTAL") & "'" + "}")
Next
jsonData.Append("]")
jsonData.Append("}")
Dim ChartOutput As New FusionCharts.Charts.Chart("column2d", MethodBase.GetCurrentMethod().Name, "100%", "300", "json", jsonData.ToString())
Literal1.Text = ChartOutput.Render()
End Sub
It is either at behind code at Statistics.aspx or Chart.aspx. Please help me, I am new with vb.net

Dynamic controls added to my content page during the preinit event do not maintain viewstate

I've added a few dynamic controls to my content page during the PreInit event, however the Viewstate is not being maintained automatically after postback, despite what is claimed about adding controls during the PreInit event. My drop down list and textbox reset. What am I doing wrong?
Mark Up
<%# Page Title="" Language="VB" MasterPageFile="~/ContentPages/MasterPage.master" AutoEventWireup="false" CodeFile="ElktonOEE.aspx.vb" Inherits="ContentPages_OEE_ElktonOEE" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder_Head" Runat="Server">
<link rel="stylesheet" href="http://flexweb/MES/css/UserControls/FlexGridView.css" type="text/css"/>
<link rel="stylesheet" href="http://flexweb/MES/css/LabelTexbox.css" type="text/css"/>
<link rel="stylesheet" href="http://flexweb/MES/css/OEE.css" type="text/css"/>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder_PageContentTitle" Runat="Server">
<div class="PageContentTitle">OEE Report</div>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ContentPlaceHolder_Content" Runat="Server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<script type="text/javascript">
</script>
<div class="MESContentDiv" id="SqlQueryContentDiv">
<div id="ContentLabelDiv">
<asp:Label ID="PanelLabel" runat="server" CssClass="ContentLabel"></asp:Label>
</div>
<br />
<asp:Panel ID="Panel1" runat="server">
<!-- Controls dynamically generated in the code-behind and inserted here -->
</asp:Panel>
<br />
<br />
<asp:Panel ID="Panel2" runat="server">
<asp:Table ID="Table1" runat="server">
</asp:Table>
</asp:Panel>
</div>
</asp:Content>
Code Behind
Imports ASP 'Allows User Control to be dynamically loaded onto page
Imports System.Data 'Allows namespace access to the DataSet class
Imports System.Web.UI.UserControl
Imports MES_Class_Library
Partial Class ContentPages_OEE_ElktonOEE
Inherits System.Web.UI.Page
Protected Sub Page_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
'Call this to avoid null result when searching for controls on a content page
CommonFlexwebFunctions.PrepareChildControlsDuringPreInit(Page)
'Add Dynamic Controls, Dyanimc Controls Must be given ID in order for the viewstate to work.
LoadSearchPrompt()
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Label_Debug.Visible = False
'Prompt for parameters
PanelLabel.Text = "Select OEE Parameters"
'Check for empty Query String
If (Request.QueryString("Type") IsNot Nothing) And (Request.QueryString("Date") IsNot Nothing) Then
Select Case Request.QueryString("Type")
Case "Daily"
LoadDailySummary()
Case "Weekly"
'LoadWeeklySummary()
Case "Monthly"
'LoadMonthlySummary()
End Select
Else
Panel2.Visible = False
End If
End Sub
Private Sub LoadSearchPrompt()
Dim lb1, lb2 As New Label
Dim ddl As New DropDownList
Dim tb As New TextBox
Dim ce As New AjaxControlToolkit.CalendarExtender
Dim validation_groupname As String = "ValidDate"
'Report Label
lb1.CssClass = "LabelName125 Twelve"
lb1.ID = "lbType"
lb1.Text = "Report Type:"
'Report DDL
ddl.CssClass = "ML5"
ddl.ID = "ddlReportType"
ddl.Items.Add("--")
ddl.Items.Add("Daily")
ddl.Items.Add("Weekly")
ddl.Items.Add("Monthly")
'Start Date Label
lb2.CssClass = "LabelName125 Twelve"
lb2.ID = "lbDate"
lb2.Text = "Start Date:"
'Start Date Textbox
tb.CssClass = "TextboxValue125 ML5"
tb.ID = "textboxStartDate"
tb.ValidationGroup = validation_groupname
'Calendar Extender
ce.ID = "ceDate"
ce.TargetControlID = "textboxStartDate"
'Valiation
Dim cv As New CompareValidator
Dim vs As New ValidationSummary
cv.ControlToValidate = "textboxStartDate"
cv.ID = "cv1"
cv.Display = ValidatorDisplay.None
cv.ErrorMessage = "Date must be in the mm/dd/yyyy format."
cv.Operator = ValidationCompareOperator.DataTypeCheck
cv.Type = ValidationDataType.Date
cv.ValidationGroup = validation_groupname
vs.ID = "vs1"
vs.HeaderText = "The data you entered contains an error."
vs.ShowMessageBox = True
vs.ShowSummary = False
vs.ValidationGroup = validation_groupname
'Submit
Dim btn As New Button
btn.CssClass = "Button100 LeftMargin25"
btn.ID = "btnSubmit"
btn.CausesValidation = True
btn.ValidationGroup = validation_groupname
btn.Text = "Submit"
'add handler
AddHandler btn.Click, AddressOf MyBtnClick '' this is the method to call
'Add Controls
Panel1.Controls.Add(lb1)
Panel1.Controls.Add(ddl)
Panel1.Controls.Add(lb2)
Panel1.Controls.Add(tb)
Panel1.Controls.Add(ce)
Panel1.Controls.Add(cv)
Panel1.Controls.Add(vs)
Panel1.Controls.Add(btn)
End Sub
Private Sub MyBtnClick(ByVal sender As Object, ByVal e As EventArgs)
Dim btn As Button = CType(sender, Button) ''Gets the button that fired the method
Dim ReportType As String = ""
Dim StartDate As String = ""
'Access the ddl
Dim ddl As DropDownList = CType(CommonFlexwebFunctions.RecursiveFindControl(Page, "ddlReportType"), DropDownList)
'If the proper ddl was found, set its value
If ddl IsNot Nothing Then
'Set the value
ReportType = ddl.SelectedItem.ToString()
End If
'Access the tb
Dim tb As TextBox = CType(CommonFlexwebFunctions.RecursiveFindControl(Page, "textboxStartDate"), TextBox)
'If the proper ddl was found, set its value
If tb IsNot Nothing Then
'Set the value
StartDate = tb.Text
End If
Response.Redirect("ElktonOEE.aspx?Type=" + ReportType + "&Date=" + StartDate)
End Sub
Private Sub LoadDailySummary()
Panel2.Visible = True
End Sub
End Class
Class Functions
Public Class CommonFlexwebFunctions
Public Shared Function RecursiveFindControl(container As Control, name As String) As Control
If Not (container.ID Is Nothing) AndAlso (container.ID.Equals(name)) Then
Return container
End If
For Each c As Control In container.Controls
Dim ctrl As Control = RecursiveFindControl(c, name)
If Not ctrl Is Nothing Then
Return ctrl
End If
Next
Return Nothing
End Function
Public Shared Sub PrepareChildControlsDuringPreInit(page As Page)
' Walk up the master page chain and tickle the getter on each one
' Run this so you can see the controls on content pages
Dim master As MasterPage = page.Master
While master IsNot Nothing
master = master.Master
End While
End Sub
End Class
The problem might be related to the fact that ToolkitScriptManager by default uses host aspx page url to reference it's controls scripts. Thus page's PreInit event is executed twice.
In order to avoid it - just follow the instruction provided below to instruct ScriptManager to use it's handler instead of the page's URL
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ToolkitScriptManager/ToolkitScriptManager.aspx

display uploded image in image control

i want to upload an image to a folder which is in my website's folder and then save it's path to database and display the uploaded image in control image.
when i executed my page the image is uploaded succefully and it's saved to database but it dosent displayed on the image control.
this is my view :
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Image ID="Image1" runat="server" Height="91px" Width="145px" />
</form>
<p>
</p>
</body>
</html>
and this is my code :
Imports System.Data.SqlClient
Imports System.IO
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Dim cn As SqlConnection
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If FileUpload1.PostedFile IsNot Nothing Then
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
'Save files to disk
FileUpload1.SaveAs(Server.MapPath("~/im/" & FileName))
'Add Entry to DataBase
Dim strQuery As String = "insert into dbo.images" & " values(#FileName, #FilePath)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#FileName", FileName)
cmd.Parameters.AddWithValue("#FilePath", "~/im/" & FileName)
cmd.CommandType = CommandType.Text
cmd.Connection = cn
Try
cn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cn.Close()
cn.Dispose()
End Try
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cn = New SqlConnection("server=SEVO-PC;initial catalog=controle;integrated security=true")
End Sub
Protected Sub FileUpload1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles FileUpload1.Load
Image1.ImageUrl = "im/" & FileUpload1.FileName
End Sub
End Class
Try the following edit
Protected Sub FileUpload1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles FileUpload1.Load
Image1.ImageUrl = Server.MapPath("/im/") & FileUpload1.FileName
End Sub

Using SqlBulkCopy SqlRowsCopied to update a label

I have a simple web application that is reading records from a CSV file and storing them in a database table. Then I am using SqlBulkCopy to copy the records into an SQL database using batches. All is fine with the insert. I am trying to give the user some feedback using OnSqlRowsCopied and NotifyAfter. The goal is to update a label that is contained in an UpdatePanel to display the number of records copied at the current NotifyAfter interval. However, the label will not update until SqlBulkCopy has complete. I can see that the s_OnSqlRowsCopied event is firing using Debug.WriteLine. What is the reason why the label won't update and how can I overcome this?
Code Behind
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Dim filePath As String
Dim rowsCopied As String
Public Sub btnGetCSV_Click(sender As Object, e As EventArgs) Handles btnGetCSV.Click
filePath = System.IO.Path.GetFullPath(fileUpload1.PostedFile.FileName)
lblInfo.Text = filePath
End Sub
Protected Sub btnToSQL_Click(sender As Object, e As EventArgs) Handles btnToSQL.Click
Dim cs As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("csMediaPortal").ConnectionString
CopyData(CSVtoDataTable(lblInfo.Text.ToString()), cs)
End Sub
Private Function CSVtoDataTable(filePath As String) As DataTable
Dim dt As DataTable = Nothing
Dim sourcePath As String = String.Empty
Dim csvFile As String = String.Empty
Dim conString As String = String.Empty
Dim conn As OleDb.OleDbConnection = Nothing
Dim adapter As OleDb.OleDbDataAdapter = Nothing
Dim selString As String = String.Empty
Try
sourcePath = System.IO.Path.GetDirectoryName(filePath)
csvFile = System.IO.Path.GetFileName(filePath)
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sourcePath & ";Extended Properties=""text;HDR=No;FMT=FixedLength"""
conn = New OleDb.OleDbConnection(conString)
selString = "Select * From " & csvFile
adapter = New OleDb.OleDbDataAdapter(selString, conn)
dt = New DataTable(System.IO.Path.GetFileNameWithoutExtension(filePath))
conn.Open()
adapter.Fill(dt)
conn.Close()
Catch ex As Exception
lblInfo.Text = ex.Message
Finally
adapter.Dispose()
conn.Dispose()
End Try
Return dt
End Function
Protected Sub CopyData(sourceTable As DataTable, cs As String)
Using s As SqlBulkCopy = New SqlBulkCopy(cs, SqlBulkCopyOptions.UseInternalTransaction)
s.DestinationTableName = "test"
s.BatchSize = 1000
Try
AddHandler s.SqlRowsCopied, AddressOf s_OnSqlRowsCopied
s.NotifyAfter = 900
s.WriteToServer(sourceTable)
Catch ex As Exception
DirectCast(DirectCast(HttpContext.Current.Handler, Page).FindControl("lblInfo"), Label).Text = "Commit Error: " & ex.Message
End Try
s.Close()
End Using
End Sub
Protected Sub s_OnSqlRowsCopied(sender As Object, e As SqlRowsCopiedEventArgs)
Me.lblProgress.Value = e.RowsCopied.ToString()
Me.UpdatePanel1.Update()
Debug.WriteLine(e.RowsCopied)
End Sub
End Class
Web Form
<%# Page Language="vb" CodeBehind="WebForm1.aspx.vb" Inherits="CSVUpload.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:FileUpload ID="fileUpload1" runat="server" />
<asp:Button ID="btnGetCSV" runat="server" Text="Post" OnClick="btnGetCSV_Click" />
<asp:Label ID="lblInfo" runat="server" Text="Label"></asp:Label>
</div>
<asp:Button ID="btnToSQL" runat="server" Text="Insert To SQL" OnClick="btnToSQL_Click" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<input runat="server" type="text" id="lblProgress" value="0" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

Dynamically created buttons not calling function on postback

In my visual basic web application I have a list of generated buttons that are supposed to allow the download of a file on click.
I had the example working with generated buttons on pageload, but all of a sudden the download function stopped getting called on post back, and now all the button click does (for any of the buttons) is cause a page post back.
My code:
Public folder As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
folder = "Main"
PopulateFiles(folder)
End If
End Sub
Protected Sub PopulateFiles(ByVal folder As String)
Dim myConnection As SqlConnection
Dim conString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim myCommand As SqlCommand
Dim myDataReader As SqlDataReader
Dim text As String
Dim size As Decimal
Dim name As String
Dim type As String
Dim id As Integer
folderName.Text = folder
container.Controls.Clear()
myConnection = New SqlConnection(conString)
myConnection.Open()
myCommand = New SqlCommand("Uploads_GetAllFiles", myConnection)
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#folder", folder)
Try
myDataReader = myCommand.ExecuteReader()
If myDataReader.HasRows Then
Do While myDataReader.Read()
name = myDataReader.Item("Name")
type = myDataReader.Item("Type")
id = myDataReader.Item("File_ID")
size = Math.Round(myDataReader.Item("Size") / 1000, 2)
container.Controls.Add(New LiteralControl("<div class='newRow'>"))
text = "<div class='fileName'>" & name & "</div>"
container.Controls.Add(New LiteralControl(text))
text = "<div class='fileType'>" & type & "</div>"
container.Controls.Add(New LiteralControl(text))
text = "<div class='fileSize'>" & size.ToString() & "kb</div>"
container.Controls.Add(New LiteralControl(text))
container.Controls.Add(New LiteralControl("<div class='fileDownload'>"))
Dim newBtn As New Button
newBtn.ID = "link" & id
newBtn.Text = "Download"
newBtn.CssClass = "newbie"
AddHandler newBtn.Click, AddressOf Retreive_Doc
newBtn.CommandArgument = id
container.Controls.Add(newBtn)
container.Controls.Add(New LiteralControl("</div>"))
container.Controls.Add(New LiteralControl("<div class='fileDelete'>"))
Dim newDelBtn As New Button
newDelBtn.ID = "delete" & id
newDelBtn.Text = "Delete"
newDelBtn.CssClass = "delBtn"
AddHandler newDelBtn.Click, AddressOf Retreive_Xls
newDelBtn.CommandArgument = id
container.Controls.Add(newDelBtn)
container.Controls.Add(New LiteralControl("</div>"))
container.Controls.Add(New LiteralControl("</div>"))
Loop
End If
Catch ex As Exception
MsgBox(ex.ToString())
Finally
myConnection.Close()
End Try
End Sub
Protected Sub Retreive_Doc(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click
Dim button As Button = sender
Dim id As Integer = button.CommandArgument
Dim cmd As SqlCommand = New SqlCommand("Uploads_GetFile")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", id)
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Sub
I could show the functions called from this function, but the initial function isn't even being called so I'm not sure there is a point.
My HTML is as follows:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:FileUpload ID="upload1" runat="server" /><asp:Button ID="test1" runat="server" Text="Upload" />
<asp:TextBox ID="folderTag" runat="server" ></asp:TextBox>
<asp:Button ID="search" runat="server" Text="Search" />
<asp:Label ID="folderName" runat="server">General</asp:Label><br />
<div id="navContainer" runat="server">
</div>
<div id="hiddenContent">
<asp:LinkButton ID="LinkButton1" CssClass="hide" runat="server" OnClick = "Retreive_Doc">Download Doc</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" CssClass="hide" runat="server" OnClick = "Retreive_Xls">Download xls</asp:LinkButton>
</div>
<div id="container" runat="server">
</div>
</form>
As I said before. This was working a few days ago and through the course of adding some other functionality somehow I lost it.
I'm unsure of why it posts back without calling any function.
Thanks for any help!
You need to recreate the controls with same ID in post back if you created them dynamically. Otherwise, they will disappear after postback.
Remove If Not IsPostBack Then in page load event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
folder = "Main"
PopulateFiles(folder)
End Sub
Another thought:
Is there a reason not to use CommandEvent instead of Click event if you want CommandArgument?
Again, Is there a reason not to use PlaceHolder instead of <div id="container" runat="server">?
AddHandler newBtn.Command, AddressOf Retreive_Doc
newBtn.CommandArgument = id
....
protected void Retreive_Doc(object sender, CommandEventArgs e)

Resources