Problems with loading value after postback - asp.net

I got a toolbar with different actions the user can start. In the user interface it looks like:
If I press on the "Ok" button the value will not known at the backend. My code structure is the following:
Configuration of an action
<Action Id="MyAction" Name="Action with Form">
<Form>
<asp:TextBox xmlns:asp="System.Web.UI.WebControls" ID="txtValue" runat="server" />
</Form>
</Action>
ASPX-File
<asp:Content ContentPlaceHolderID="cphToolbar" Runat="Server">
<asp:PlaceHolder ID="plhToolbar" runat="server" />
</asp:Content>
VB-File to the ASPX-File
Partial Class Form
Inherits UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.plhToolbar.Controls.Add(Me.CreateActionToolbar(<XML configuration element for the toolbar>))
End Sub
End Class
Page base class
Namespace UI
Public MustInherit Class Page
Inherits System.Web.UI.Page
Protected Overridable Function CreateActionToolbar(source As XmlElement) As Interfaces.IActions
Dim oAction As Interfaces.IActions = Me.LoadControl("~/Controls/Toolbar/Actions.ascx")
For Each element As XmlElement In source.SelectNodes("node()").OfType(Of XmlElement)()
Dim NewItem As New Controls.ActionItem
'set settings for the toolbar element
'add fields to form
For Each Item As XmlNode In element.SelectNodes("Form/node()", oNamespaceManager)
If (TypeOf Item Is XmlElement) Then
If (NewItem.Fields Is Nothing) Then NewItem.Fields = New List(Of XmlElement)
NewItem.Fields.Add(Item)
End If
Next
oAction.Items.Add(NewItem)
Next
Return oAction
End Function
End Class
End Namespace
Action user control
Partial Class Actions
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each Item As ActionItem In Me.Items
'set settings for action
If (Not (Item.Fields Is Nothing)) Then
Dim oPanel As New Panel
oPanel.ID = "dlgActionPanel" & Me.dlgAction.Controls.Count
Me.dlgAction.Controls.Add(oPanel)
Dim oFields As New Panel
oFields.ID = oPanel.ID & "_Controls"
For Each Field As XmlElement In Item.Fields
Dim oControl As System.Web.UI.Control = Nothing
Try
oControl = Me.ParseControl(Field.OuterXml)
Catch ex As Exception
oControl = New LiteralControl("<font style=""color:red;"">" & ex.Message & "</font>")
End Try
oFields.Controls.Add(oControl)
Next
Dim pnlResult As New Panel
Dim btnOk As New Button
btnOk.ID = "btnOk_" & oPanel.ID
AddHandler btnOk.Click, AddressOf Ok_Click
btnOk.Attributes.Add("onclick", "ShowWaitDialog();")
btnOk.Attributes.Add("ItemId", NewAnchor.Attributes("ItemId"))
btnOk.UseSubmitBehavior = False
btnOk.Text = Me.AcceptDialogText
pnlResult.Controls.Add(btnOk)
Dim btnCancel As New Button
btnCancel.Attributes.Add("onclick", "ShowWaitDialog();$('#" & oPanel.ClientID & "').dialog('close');CloseWaitDialog();return false;")
btnCancel.Text = Me.CancelDialogText
pnlResult.Controls.Add(btnCancel)
oPanel.Controls.Add(oFields)
oPanel.Controls.Add(pnlResult)
Dim strMessageControlId As String = oPanel.ClientID
strClientScript &= "$(""#" & strMessageControlId & """).dialog({" & NewLine
strClientScript &= " bgiframe:true, " & NewLine
strClientScript &= " autoOpen:false, " & NewLine
strClientScript &= " modal:true, " & NewLine
strClientScript &= " closeOnEscape:false, " & NewLine
strClientScript &= " width:600, " & NewLine
strClientScript &= " height:450, " & NewLine
strClientScript &= " minWidth:450, " & NewLine
strClientScript &= " minHeight:300, " & NewLine
If (Not (Item.Description Is Nothing)) Then strClientScript &= " title:'" & Item.Description & "', " & NewLine
strClientScript &= " open: function(event, ui) { $("".ui-dialog-titlebar-close"").hide(); } " & NewLine
strClientScript &= "});" & NewLine
If (String.IsNullOrEmpty(NewAnchor.Attributes("onclick"))) Then NewAnchor.Attributes.Add("onclick", String.Empty)
NewAnchor.Attributes("onclick") &= "$('#" & oPanel.ClientID & "').dialog('open');"
End If
Next
End Sub
Private Sub Ok_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim oDialog As Panel = Nothing
If (Not (String.IsNullOrEmpty(sender.ID))) Then oDialog = Me.dlgAction.FindControl(sender.ID.Substring(sender.ID.IndexOf("_") + 1) & "_Controls")
Dim oAction As ActionItem = Items.Find(Function(item) item.ItemId = sender.Attributes("ItemId"))
If (Not (oDialog Is Nothing)) Then
For Each Field As XmlElement In oAction.Fields
Dim oControl As WebControl = Nothing
If (Not (Field.SelectSingleNode("#Id|#ID") Is Nothing)) Then oControl = oDialog.FindControl(Field.SelectSingleNode("#Id|#ID").Value)
If (Not (oControl Is Nothing)) Then
Dim oParameter As SqlClient.SqlParameter = oAction.Parameters.Find(Function(item) item.ParameterName = "#" & oControl.ID.Substring(3))
If (Not (oParameter Is Nothing)) Then
Select Case oControl.GetType.ToString
Case GetType(TextBox).ToString
'After postback the value is empty!!!
If (Not (String.IsNullOrEmpty(CType(oControl, TextBox).Text))) Then oParameter.Value = CType(oControl, TextBox).Text
'more controls
Case Else
End Select
End If
End If
Next
End If
End Sub
End Class
Where is the fault that the value of the TextBox is after PostBack empty and not set because of the View State?
Thanks for any response.

I could solve it. The problem was that the jQuery dialog was not PostBack save. The solution was
$("#dialog").dialog({
appendTo:'form:first'
});

Related

Dynamic required validator and textboxes not firing inside panel

I am having a problem with validation. I created a dynamic textboxes with corresponding dynamic numeric validator but it's not firing....
Here is my code
code behind on_load
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
For i = 0 To AssetByDimension(oVal).Rows.Count - 1
Dim lt As New Literal()
Dim label As New Label()
Dim count As Integer = pnlDimension.Controls.OfType(Of Label)().ToList().Count
label.Text = "<b>" + AssetByDimension(oVal).Rows(i)("Dimension_Type") + " (" + AssetByDimension(oVal).Rows(i)("Unit_Of_Measure_Code") + "): </b>"
pnlDimension.Controls.Add(label)
Dim textbox As New TextBox()
count = pnlDimension.Controls.OfType(Of TextBox)().ToList().Count
textbox.ID = "txtDimension" & i
pnlDimension.Controls.Add(textbox)
Dim vdr As New RegularExpressionValidator
vdr.ControlToValidate = "txtDimension" & i
vdr.ValidationExpression = "\d+"
vdr.ErrorMessage = "Numbers only"
vdr.BorderColor = Drawing.Color.Red
vdr.ForeColor = Drawing.Color.Red
vdr.SetFocusOnError = True
pnlDimension.Controls.Add(vdr)
lt.Text = "<br /><br />"
pnlDimension.Controls.Add(lt)
Next
End Sub
and here's the button event handler
Protected Sub btnSaveDim_Click(sender As Object, e As EventArgs)
if Page.isvalid then
Response.Redirect("AddAsset.aspx")
else
'do nothing...
end
End Sub
What I have tried:
I tried to use Page.isValid but is not working...
Hoping for your kind

Gridview format issue after show message

I have a Gridview, and one button.
when i click button then show message, but after that my Gridview's format is not correct as before.
please view more in below picture:
Gridview incorrect format after close message
I using this code below to show message:
HttpContext.Current.Response.Write("<script>alert('Đã tồn tại nguồn đơn " & name & ". Bạn không thể tạo thêm được nguồn đơn này nữa')</script>")
Return
=> How to keep previos format?
This code below i using:
Private Sub grvData_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvData.RowCommand
lblError.Text = String.Empty
Dim commandNameType As String = String.Empty
Try
If e.CommandName = "Insert" Then
commandNameType = "thêm"
Dim txtName As TextBox = DirectCast(grvData.FooterRow.FindControl("txtNewName"), TextBox)
Dim cboStatus As DropDownList = DirectCast(grvData.FooterRow.FindControl("ddlNewStatus"), DropDownList)
lblError.Text = String.Empty
Try
If String.IsNullOrEmpty(txtName.Text) Then
Return
End If
Dim pSource As New TblPetitionSource
pSource.Name = txtName.Text
pSource.Lastupdate = Now.ToString("yyyy/MM/dd HH:mm:ss")
pSource.StatusFlag = 1
pSource.UpdateBy = "ADMIN"
Dim db As New ProcuracyDataContext
Dim lst = (From p In db.TblPetitionSource Where p.Name = txtName.Text Select p).ToList()
If lst.Count > 0 Then
HttpContext.Current.Response.Write("<script>alert('Đã tồn tại nguồn đơn . Bạn không thể tạo thêm được nguồn đơn này nữa')</script>")
Return
End If
db.TblPetitionSource.InsertOnSubmit(pSource)
db.SubmitChanges()
BindData()
Catch ex As Exception
lblError.Text = ex.Message
End Try
End If
Catch ex As Exception
lblError.Text = "Lỗi không " & commandNameType & " được bản ghi này <br />" & ex.Message
End Try
End Sub
This is my code using for MergeCells:
Private Sub grvData_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grvData.RowDataBound
Try
If e.Row.RowType = DataControlRowType.Header Then
e.Row.Cells.RemoveAt(e.Row.Cells.Count - 1)
e.Row.Cells(e.Row.Cells.Count - 1).ColumnSpan = 2
e.Row.Cells(e.Row.Cells.Count - 1).Text = "Thao tác"
End If
If e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells.RemoveAt(e.Row.Cells.Count - 1)
e.Row.Cells.RemoveAt(e.Row.Cells.Count - 1)
e.Row.Cells.RemoveAt(e.Row.Cells.Count - 1)
e.Row.Cells(e.Row.Cells.Count - 1).ColumnSpan = 4
End If
Catch ex As Exception
Throw New Exception(ex.Message, ex)
End Try
End Sub
Could you see more detail at these files:
https://drive.google.com/open?id=0B6NcrBkoDTV5TV9QcFFUWUpnTFk
and the form after click button:
Web form after click button
Thanks you so much!

generate html/asp dynamically

I have a treeview type structure of folders/links that's populated from a table. What I was attempting to do was procedural loop through my recordset and generate my html in page_init and then try and bind the controls. When I try to add the link buttons to the placeholders in html, it can never seem to find them.
I might be missing something fundamental here, all the examples i've seen bind a control thats already on the page, am I unable to generate the html myself in page_init?
example
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
content_div.Innerhtml = "<asp:PlaceHolder id=""test"" runat=""server"" ></asp:PlaceHolder>"
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim _linkb As New LinkButton
_linkb.ID = "lb_cat_" & cat.uID
_linkb.Attributes.Add("href", "javascript: sltoggle('cat_" & cat.uID & "');")
_linkb.Attributes.Add("Text", "Expand/Close")
_linkb.Attributes.Add("runat", "server")
Dim ph As PlaceHolder = DirectCast(TRIEDEVERYTHINGUNDERTHESUN.FindControl("test"), PlaceHolder)
ph.Controls.Add(_linkb)
End Sub
If someone could point me in the right direction it'd be much appreciated
Regards,
Pete
UPDATE - full code
Private Sub load_dynamic_file_view()
Dim _sb As New StringBuilder
Dim _sfc As New sf_file_category, _sff As New sf_file
_lsfc = _sfc.get_all_sf_file_category
_lsff = _sff.get_active_sf_files
Dim _list_root As List(Of sf_file_category) = _lsfc.FindAll(Function(p) p.parent_id = 0)
If Not _list_root Is Nothing Then
_sb.Append("<strong>File Downloads</strong><br />")
_sb.Append("<div class=""indent-me"" ><br />")
For Each cat As sf_file_category In _list_root
'header/Open Link
Dim _linkb As New LinkButton
_linkb.ID = "lb_cat_" & cat.uID
_linkb.Attributes.Add("href", "javascript: sltoggle('cat_" & cat.uID & "');")
_linkb.Attributes.Add("Text", "Expand/Close")
_linkb.Attributes.Add("runat", "server")
Dim ph As PlaceHolder = DirectCast(Me.Master.FindControl("lb_cat_" & cat.uID), PlaceHolder)
ph.Controls.Add(_linkb)
_sb.Append(HtmlDecode(cat.name) & " <Asp:PlaceHolder id=""lb_cat_" & cat.uID & """ runat=""server"" /><br />")
'_sb.Append("<div id=""cat_" & cat.uID & """ class=""toggle-hide"">")
'_sb.Append(add_child_folder(cat.uID, content))
'_sb.Append(show_files(cat.uID, content))
'_sb.Append("</div><div class=""clearfix"" />")
Next
_sb.Append("</div>")
_sb.Append("<br /><br />")
End If
content_div.InnerHtml = _sb.ToString
End Sub
Private Function add_child_folder(ByVal catid As Long, ByRef content As ContentPlaceHolder) As String
Dim _sb As New StringBuilder
Dim _cl As List(Of sf_file_category) = _lsfc.FindAll(Function(p) p.parent_id = catid)
If Not _cl Is Nothing Then
_sb.Append("<div class=""indent-me"" ><br />")
'For Each _c As sf_file_category In _cl.OrderBy(Function(p) p.view_order)
_cl.Sort(Function(c1 As sf_file_category, c2 As sf_file_category)
Return c1.view_order.CompareTo(c2.view_order)
End Function)
For Each cat As sf_file_category In _cl
Dim _linkb As New LinkButton
_linkb.ID = "lb_cat_" & cat.uID
_linkb.Attributes.Add("href", "javascript: sltoggle('cat_" & cat.uID & "');")
_linkb.Attributes.Add("Text", "Expand/Close")
_linkb.Attributes.Add("runat", "server")
Content.Controls.Add(_linkb)
_sb.Append(HtmlDecode(cat.name) & " <Asp:LinkButton id=""lb_cat_" & cat.uID & """ runat=""server"" Text=""Expand/Close"" href='javascript: sltoggle('cat_" & cat.uID & "');' /><br />")
'_sb.Append("<div id=""cat_" & cat.uID & """ class=""toggle-hide"">")
_sb.Append(add_child_folder(cat.uID, content))
_sb.Append(show_files(cat.uID, content))
'_sb.Append("</div><div class=""clearfix"" >")
Next
_sb.Append("</div><br />")
End If
Return _sb.ToString
End Function
Private Function show_files(ByVal catid As Long, ByRef content As ContentPlaceHolder) As String
Dim _sb As New StringBuilder
Dim _fl As List(Of sf_file) = _lsff.FindAll(Function(p) p.file_category = catid)
If Not _fl Is Nothing Then
_sb.Append("<div class=""indent-me"" ><br />")
For Each _f As sf_file In _fl
Dim _linkb As New LinkButton
_linkb.ID = "file_" & _f.uID
_linkb.Attributes.Add("onCommand", "download_file")
_linkb.Attributes.Add("CommandArgument", _f.uID.ToString)
_linkb.Attributes.Add("Text", _f.file_name)
_linkb.Attributes.Add("runat", "server")
AddHandler _linkb.Command, AddressOf download_file
content.Controls.Add(_linkb)
_sb.Append("<asp:LinkButton id=""file_" & _f.uID & """ runat=""server"" onCommand=""download_file"" commandArgument=""" & _f.uID & """ Text=""" & _f.file_name & """ /><br />")
Next
_sb.Append("</div><br />")
End If
Return _sb.ToString
End Function
What your full code shows is that your building a massive string of HTML. This is fine for some smaller situations, but your code is clearly getting quite big now, and I would suggest you change this approach.
I would recommend that you declare web control equivalents, such as:
new HtmlGenericControl("div") instead of <div></div>
OR
new HtmlAnchor() OR new LinkButton() instead of <a></a>
In the example of a tree structure the HTML may look like this:
<ul>
<li>
ROOT
<ul>
<li>
LEVEL 1
</li>
</ul>
</li>
</ul>
To generate this in code you would do something similar to:
'Menu Holder
Dim treeStruct As HtmlGenericControl("ul")
'Root
Dim branch As HtmlGenericControl("li")
Dim branchItem as HtmlAnchor("a")
'Level 1
Dim subLevel As HtmlGenericControl("ul")
Dim subBranch As HtmlGenericControl("li")
Dim subBranchItem as HtmlAnchor("a")
'Setup Level 1
subBranchItem.InnerText = "LEVEL 1"
subBranchItem.Href = "levelone"
subBranch.Controls.Add(subBranchItem)
subLevel.Controls.Add(subBranch)
'Setup Root
branchItem.InnerText = "ROOT"
branchItem.Href = "root.htm"
'Add Link To Root
branch.Controls.Add(branchItem)
'Add Sub Branch To Root
branch.Controls.Add(subLevel)
treeStruct.Controls.Add(branch)
Important The code above is just for examples sake, ideally you would separate the functionality into functions for branch creation and then loop through your elements with your for loop.
You will also notice that I have used an <UL> instead of <DIV> as I would consider a tree structure to be an un-ordered list. Plus, you will also get the styling benefit from this more ridged structure.
I hope this helps
You generate only HTML tags and do not generate ASP.Net tags, as they can't be parsed by browser.
I think your code should be like
content_div.Innerhtml = "<div id='test'></div>"
ASP:Placeholder control is just a place holder and it is not equal to div HTML tag.
For an example i gave div tag here.
asp.net controls added as text are not known to the page and thus no viewstate / object is stored for it, thus you can never find it using Findcontrol.
Use the object of the control and add it to the parent control's Control collection
e.g.
div.Controls.Add(new PlaceHolder() { ... });
Once you have added it before Render event , its state will be saved and accessable.
It looks like your trying to add a placeholder to the content_div, however, what you are doing is rendering the tag as HTML content.
I don't know exactly what type of control content_div is, but can't you try:
content_div.controls.add(new placeholder() { ID = "test" });
This would then allow you to find the control within the content_div control.
However, what would probably be a much more concise solution for you might be the following:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim _linkb As New LinkButton
_linkb.ID = "lb_cat_" & cat.uID
_linkb.Attributes.Add("href", "javascript: sltoggle('cat_" & cat.uID & "');")
_linkb.Attributes.Add("Text", "Expand/Close")
//you don't need this when using code behind
//_linkb.Attributes.Add("runat", "server")
//this will add your linkbutton to the content_div control
content_div.Controls.Add(_linkb)
End Sub
Give this ago and you should find it to be a useful way of dynamically building your page with asp controls.

This code will display selected checkboxes text in textbox as 1,2,3,4,5,6,7,8,9

This code will display selected checkboxes Text in textbox as in the order i checked it 1,2,3,4,5,6,7,8,9
But it will not display selected checkboxes Text in textbox after 9
Partial Class _45seater_WebUserControl
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim str As String = Nothing
Dim id As String = Nothing
Dim ch As String = Nothing
For Each ctrl As Control In Panel1.Controls
If ctrl.GetType() Is GetType(CheckBox) Then
Dim chk As CheckBox = ctrl
UpdatePanel1.FindControl("chk")
If chk.Checked = True Then
If TextBox1.Text = "" Then
TextBox1.Text = chk.Text
Else
Dim SearchString As String = chk.Text
id = TextBox1.Text
If id.Contains(SearchString) <> -1 Then
TextBox1.Text = TextBox1.Text + "," + chk.Text
Else
End If
End If
Else
Dim SearchString As String = chk.Text
id = TextBox1.Text
If id.Contains(SearchString) <> -1 Then
Else
id = RemoveSubString(id, chk.Text)
TextBox1.Text = id
End If
End If
End If
Next
End Sub
Private Function RemoveSubString(ByVal stringvalue As String, ByVal stringremove As String) As String
Dim pos As Integer = stringvalue.IndexOf(stringremove)
If pos > 0 Then
Return stringvalue.Remove(pos - 1, stringremove.Length + 1)
ElseIf pos = 0 Then
If stringvalue.Contains(",") <> -1 Then
Return stringvalue.Remove(pos, stringremove.Length)
Else
Return stringvalue.Remove(pos, stringremove.Length + 1)
End If
End If
Return stringvalue
End Function
End Class
can any body show after chekbox10,checkbox11,checkbox12 in text box as 10,11,12 ......so on using this code
I really don't understand that requirement but i think the only thing the function should do is to print the ID's of all checked CheckBoxes in a TextBox.
Why do you complicated it, this works too:
TextBox1.Text = String.Empty
For Each control As Control In form1.Controls
If TypeOf control Is CheckBox AndAlso DirectCast(control, CheckBox).Checked Then
TextBox1.Text &= control.ID & ","
End If
Next
'remove last comma'
If TextBox1.Text.Length <> 0 Then TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1)
According to your new informations about the order, try this:
Protected Sub CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim chk As CheckBox = DirectCast(sender, CheckBox)
Dim separator As Char = ","c
If TextBox1.Text.Length <> 0 Then
Dim allIIDs As New List(Of String)(TextBox1.Text.Split(separator))
allIIDs.Remove(chk.ID)
If chk.Checked Then
allIIDs.Add(chk.ID)
End If
TextBox1.Text = String.Empty
For Each id As String In allIIDs
TextBox1.Text &= id & separator
Next
TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1)
Else
TextBox1.Text = chk.ID
End If
End Sub
To register the CheckedChanged-Event on the CheckBoxes you have to add following on aspx for every Checkbox:
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="CheckedChanged" />
or if you are lazy and want to do that in Codebehind, add following in Page_Init:
Private Sub WebForm1_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
For Each control As Control In Me.form1.Controls
If TypeOf control Is CheckBox Then
Dim chk As CheckBox = DirectCast(control, CheckBox)
chk.AutoPostBack = True
AddHandler chk.CheckedChanged, AddressOf CheckedChanged
End If
Next
End Sub

concatenate filenames

I have the following code in child window which is working but what I want to do is instead of using response.write I want to use label control or to display all the filename like this:
music.pdf, inventory.doc
My Ultimate goal is to pass the values in string (e.g.: "music.pdf, inventory.pdf" ) to the parent window.
How do I do it?
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Try
'' Get the HttpFileCollection
Dim hfc As HttpFileCollection = Request.Files
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("/ServerName/DirectoryName") & "\"" & System.IO.Path.GetFileName(hpf.FileName))
Response.Write("<b>File: </b>" & hpf.FileName & " <b>Size:</b> " & hpf.ContentLength & " <b>Type:</b> " & hpf.ContentType & " Uploaded Successfully! <br/>")
Else
Response.Write("Please select a file to upload.")
End If
Next i
Catch ex As Exception
End Try
End Sub
This is not the way I would do it but you asked for your code to work with a Label.
ASPX:
<asp:Label id="lblUploadMsg" runat="server" visible="false"></asp:Label>
Code:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Try
'' Get the HttpFileCollection
Dim hfc As HttpFileCollection = Request.Files
lblUploadMsg.Text = String.empty
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("/ServerName/DirectoryName") & "\"" & System.IO.Path.GetFileName(hpf.FileName))
lblUploadMsg.Visible = True;
lblUploadMsg.Text +="<b>File: </b>" & hpf.FileName & " <b>Size:</b> " & hpf.ContentLength & " <b>Type:</b> " & hpf.ContentType & " Uploaded Successfully! <br/>"
Else
lblUploadMsg.Text="Please select a file to upload."
End If
Next i
''HTML Encode lblUploadingMsg.Text after
Catch ex As Exception
End Try
End Sub
Consider using a <asp:BulletedList>, which is an ASP.NET server control for an unordered list <ul>.
ASPX:
<asp:BulletedList
id="uploadedFiles" runat="server"></asp:BulletedList>
Instead of Response.Write() each file, simply:
Dim displayText as String = string.Format("File: {0} Size: {1} Type: {2} Uploaded Successfully", _
hpf.FileName ,hpf.ContentLength ,hpf.ContentType)
uploadedFiles.Items.Add(New ListItem(displayText, hpf.FileName ))
Add a label control onto the form/control and then instead of using Response.Write, why not use a string builder and append all of the output to that in the loop. Once you have processed all of the files set the Label control's Text property of the string builder ToString method.
Hope this helps
You can use one of the String.Join() overloads.
Use a string builder to join strings. Strings in .NET are immutable, so Join and any other operators are memory intensive
Comment (not on the question, but I noticed it in your code) Use Path.Combine and any other Path functions. Amazingly easy to forget that they exist and have saved me millions of headaches.
Move your Response.Write outside of the loop over i.
Inside of i loop, keep track using a List<String>. Then, after the loop, use the Response.Write, to write a String.Join over the List.ToArray with a comma.
Using a Label control won't honour your <b> tags - what you're looking for here is to use the Literal control. Try something like this:
In your markup:
<asp:literal runat="server" id="UploadedFileInfoLiteral" />
In your code-behind:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Try
'' Get the HttpFileCollection
Dim hfc As HttpFileCollection = Request.Files
Dim FileInfoStringBuilder As System.Text.StringBuilder = New System.Text.StringBuilder
Dim hpf As HttpPostedFile
For i As Integer = 0 To hfc.Count - 1
hpf = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("/ServerName/DirectoryName") & "\"" & System.IO.Path.GetFileName(hpf.FileName))
FileInfoStringBuilder.Append("<strong>File: </strong>" & hpf.FileName & " <strong>Size:</strong> " & hpf.ContentLength & " <strong>Type:</strong> " & hpf.ContentType & " Uploaded Successfully! <br/>")
Else
FileInfoStringBuilder.Append("Please select a file to upload.")
End If
Next
UploadedFileInfoLiteral.Text = FileInfoStringBuilder.ToString()
Catch ex As Exception
End Try
End Sub

Resources