VB.NET CheckboxList doubles when button is clicked. Why? - asp.net

Every time I click the Delete Button, the check marks double in quantity:
Public Class About
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim di As New IO.DirectoryInfo("C:\Images\")
Dim imageArray As IO.FileInfo() = di.GetFiles()
Dim image As IO.FileInfo
'clear imageArray
'list the names of all images in the specified directory
For Each image In imageArray
CheckBoxList1.Items.Add(image.Name)
Next
End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDelete.Click
For count As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(count).Selected Then
File.Delete("C:\Images\" & CheckBoxList1.Items(count).ToString)
End If
Next
End Sub
End Class
The checkboxlist isn't refreshed so that the checkbox that I deleted is removed from the checkboxlist. How do I accomplish that? Thanks!

On a button click, Page_Load is ran again, so the code that adds the checkboxes is ran a second time.
Add a check for Page.IsPostBack, and only add the checkboxes if it is not a postback.
If Not Page.IsPostBack Then
For Each image In imageArray
CheckBoxList1.Items.Add(image.Name)
Next
End If
(I hope syntax is right... Not used to VB)

the whole content of the Page_Load event handler has to be executed only once in your case, so rewrite it like this:
If Not IsPostBack Then
Dim di As New IO.DirectoryInfo("C:\Images\")
Dim imageArray As IO.FileInfo() = di.GetFiles()
Dim image As IO.FileInfo
'clear imageArray
'list the names of all images in the specified directory
For Each image In imageArray
CheckBoxList1.Items.Add(image.Name)
Next
End If

Related

How do I add an on click event to image button added from code behind

I am loading all images in a folder on page load by an image button from code behind.
The images are added correctly but I want to hook up an onclick event unto the image button added dynamically.
Below is my code
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
For Each strfilename As String In Directory.GetFiles(Server.MapPath("~/glypics/"))
Dim imgbtn As New ImageButton
Dim fileinfo As New FileInfo(strfilename)
imgbtn.ImageUrl = "~/glypics/" + fileinfo.Name
imgbtn.Width = Unit.Pixel(250)
Panel1.Controls.Add(imgbtn)
imgbtn.Style.Add("padding", "3px")
Next
End Sub
I am not sure what an imagebutton is? But assuming it's anything like a button you just have to add a handler, which can be done a number of ways.
Dim imgbtn As New Button
AddHandler imgbtn.Click, Sub()
'do stuff
End Sub
Or
Dim imgbtn As New Button
AddHandler imgbtn.Click, AddressOf DoClick
Private Sub DoClick(sender As Object, e As EventArgs)
'Do Stuff
End Sub
The latter is more easily removed if needed
RemoveHandler imgbtn.Click, AddressOf DoClick
Add Addhandler imgbtn.MouseClick, AddressOf imgbtn_MouseClick in your function then create the called function.
Sub imgbtn_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs)
'Image Button clicked...
End Sub

Failure to update textbox.text

I have a relatively simple ASP.NET problem (I should think) that regrettably I am unable to solve by myself. What I am trying to do is the following:
On a page I load a number of controls (Text Boxes) programmatically;
following this load the user should be able to select a value to load into the Textbox from a panel control that is added to the page following the click of a button
Once the panel is closed, the selected text from the panel should be loaded into the textbox
However, in the vb.net statements below when run the "test" string never makes it to the textbox - any help with resolving this would be greatly appreciated.
Public Class test
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Controls_Load()
End Sub
Public Sub Controls_Load()
Dim ttf_tb As New TextBox With {.ID = "ttf_tb"}
Master_Panel.Controls.Add(ttf_tb)
Dim ttf_button As New Button
Master_Panel.Controls.Add(ttf_button)
AddHandler ttf_button.Click, AddressOf TTF_BUTTON_CLICK
End Sub
Public Sub TTF_BUTTON_CLICK(sender As Object, e As EventArgs)
Dim str As String = sender.id
Dim panel As New Panel
panel.ID = "TTF_Panel"
panel.Width = 300
panel.Height = 300
Master_Panel.Controls.Add(panel)
panel.BackColor = Drawing.Color.Black
panel.Style.Add(HtmlTextWriterStyle.Position, "absolute")
panel.Style.Add(HtmlTextWriterStyle.Left, "200px")
panel.Style.Add(HtmlTextWriterStyle.Top, "100px")
panel.Style.Add(HtmlTextWriterStyle.ZIndex, "100")
Dim CL_Button As New Button
CL_Button.ID = "TTF_Close_" & Replace(str, "TTF_Button_", "")
panel.Controls.Add(CL_Button)
AddHandler CL_Button.Click, AddressOf TTF_Close_Button_Click
End Sub
Public Sub TTF_Close_Button_Click(sender As Object, e As EventArgs)
Dim ttf_tb As TextBox = Master_Panel.FindControl("ttf_tb")
ttf_tb.Text = "Test"
Dim panel As Panel = FindControl("TTF_Panel")
Master_Panel.Controls.Remove(panel)
End Sub
End Class
I think you need to re-create your controls in the Page_Init method. It's been a while since I've done web forms but I think it's something like:
When a user clicks the button a post back is fired. This re-creates a new instance of your class, creates the controls on the page, assigns any form values then calls your Page_Load event.
The problem is you are creating your controls too late, so the forms values are never assigned correctly.
You should create / recreate your dynamic controls in the Init event:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Controls_Load()
End Sub
This should allow you to maintain their state across PostBacks.
For more information about this topic, see the MSDN article on the ASP.NET Page Life Cycle.

Asp.Net Null Reference Exception on Event Handler for Dynamic Controls

I've created some dynamic controls on page load and added an event handler to handle the click event of a dynamic link button. Within the sub of the click event handler, I need to reference some other (non-dynamic) controls on the page and change their value. However, I get a null reference exception - object not set to an instance of an object - each time I try to reference a control on the page (in this case label1). What am I doing wrong in creating these dynamic controls or with my event handler? Thanks!
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Get the data to populate the controls
Dim oMySqlData As New MySqlDataProvider
PlaceHolder1.Controls.Add(CreateExistingNotesHTML(oMySqlData.GetParentNotes("104628"), oMySqlData.GetChildNotes("104628")))
End Sub
Public Sub OnCommentClick(ByVal sender As Object, ByVal e As EventArgs)
'The event handler for the link buttons
Label1.Text = "You clicked " & DirectCast(sender, LinkButton).ID
End Sub
Public Function CreateExistingNotesHTML(ByVal dtParent As DataTable, ByVal dtChild As DataTable) As HtmlGenericControl
'The routine that creates the dynamic controls
Dim divContainer As New HtmlGenericControl("div")
For Each drParent As DataRow In dtParent.Rows()
divContainer.Controls.Add(WriteNote(drParent.Item("NoteId").ToString(), drParent.Item("UserName").ToString(), drParent.Item("ItemNote").ToString, CDate(drParent.Item("InsertDate")), "note"))
Next
Return divContainer
End Function
Private Function WriteNote(ByVal NoteId As String, ByVal UserName As String, ByVal ItemNote As String, ByVal InsertDate As DateTime, ByVal DivClass As String) As HtmlGenericControl
Dim div As New HtmlGenericControl("div")
div.ID = "d" & NoteId
div.Attributes.Add("class", DivClass)
div.Controls.Add(New LiteralControl(" ยท "))
'Add the dynamic link buttons
Dim lnkComment As New LinkButton
lnkComment.ID = "l" & NoteId
lnkComment.Text = "Comment"
lnkComment.Style("Text-decoration") = "none"
AddHandler lnkComment.Click, AddressOf oNotes.OnCommentClick
div.Controls.Add(lnkComment)
Return div
End Function
With this line
Dim oNotes As New EbayItemNotes
AddHandler lnkComment.Click, AddressOf oNotes.OnCommentClick
You are handling this event outside of your page and within the EbayItemNotes class, how does this class know anything of Label1 that resides in your page?
Could it be that you need to pass your label in as well..
Dim oNotes As EbayItemNotes = new EbayItemNotes(label1)
inside EbayItemNotes constructor
public sub New(lbl as Label) //store this label for use in event handler..

re-add your handler on every postback

when the page is loaded the following code is invoke
page load
Dim products As New LinkButton
products.Text = "Products"
testPanel.Controls.Add(products)
AddHandler products.Click, AddressOf getProducts
getProducts function
Dim testDb As New Product
Dim arr As ArrayList = testDb.DbLoop()
Dim ObjList As ProductBo
Dim ID As Integer
Dim link As LinkButton
For Each ObjtList In arr
ID= ObjtList.C_Id
link = New LinkButton
testPanel.Controls.Add(New LiteralControl("<br />"))
link.ID = ID
link.Text = ObjList.Name
link.CommandArgument = CustInt
Me.testPanel.Controls.Add(link)
AddHandler link.Click, AddressOf getProductsDetails
Next ObjList
what i want to achive when the page load i link is create Products when i click on products link it invoke an event handler call getProducts. getproducts will loop in the database to fetch all record then it will creat a link for each product name when i click on the product name it should invoke another event. my problem is how can i re add control after every postback thank u
Because the links are dynamically created, you have to re-create and re-add the handler for them on each postback.
On the _init event, you have to check the state you are in (before product load or after product load), then create either the Product Load link OR the Product Details link. Key is they have to be created EVERY postback AND they have to be created before the _Load event. Typically this should be done on the _Init event.
Something along the lines of this:
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
If ViewState.Item("ProductsLoaded") IsNot Nothing Then
If ViewState.Item("ProductsLoaded").ToString = "True" Then
GetProducts(Me, New EventArgs)
Else
CreateProductsButton()
End If
Else
CreateProductsButton()
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub CreateProductsButton()
Dim btnProducts As New LinkButton
btnProducts.Text = "Products"
testPanel.Controls.Add(btnProducts)
AddHandler btnProducts.Click, AddressOf GetProducts
ViewState.Item("ProductsLoaded") = False.ToString
End Sub
Private Sub GetProducts(sender As Object, e As EventArgs)
' get products list here
' and set handlers for each link
ViewState.Item("ProductsLoaded") = True.ToString
End Sub
Private Sub GetProductsDetails(sender As Object, e As EventArgs)
'get product details here
End Sub

problem with asp textbox control

i have a textbox control in asp.net. textbox have a search button beside it. On clicking the search button i redirect to new page with the value in textbox. the new page also hase textbox and button beside it. I set the value sent from previous page to the textbox on new page. If i change the value on new page and click the search button it should take the new value. But it takes the previous value.
on page load method wrote the following code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
str1 = Request.QueryString("str1").ToString()
flag = Request.QueryString("flg")
txtsrch.Text = str1
End Sub
On button click following code
Protected Sub bsrcnew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles bsrcnew.Click
Dim s As String
s = txtsrch.Text
If (flag.Equals(0)) Then
Response.Redirect("newSearch.aspx?str1=" + s)
ElseIf (flag.Equals(1)) Then
Response.Redirect("termsnew.aspx?str1=" + s)
End If
end sub
can any1 tell me how do i get changed value in textbox?
Try assigning it in a
If(!IsPostBack)
{
str1 = Request.QueryString("str1").ToString()
flag = Request.QueryString("flg")
txtsrch.Text = str1
}
On buttonclick its again assigning the value from query string.
Use IsPostBack to set your text box only on the first run in the second page. Example:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack
str1 = Request.QueryString("str1").ToString()
flag = Request.QueryString("flg")
txtsrch.Text = str1
End If
End Sub

Resources