Failure to update textbox.text - asp.net

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.

Related

how to redirect to another page, that generates a gridview, after clicking a button in the first page

i have some different buttons in a page after clicking them i want them to redirect me to a page that has a gridview , but for each button it gives a different gridview which are generated by datatables . may you help to find ,how can i do that in asp.net, vb ??
i did two pages at the gridview page i made methods that are binding different gridviews for each button , and in the first page where i have the button click events i did the redirecting to this gridview page and called the corresponding methods. it redirects me but doen't give me any gridview at all :(
Call in button action
Response.Redirect("Your Page Name.aspx")
and call in that page a BindGrid Function that you create to bind the gridview
You can redirect by using
Response.Redirect("GridView.aspx")
At the same time you can use only one aspx by using session
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Session.Add("CheckButton", Button1Clicked)
Response.Redirect("GridView.aspx")
End Sub
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Session.Add("CheckButton", Button2Clicked)
Response.Redirect("GridView.aspx")
End Sub
After that at your GridView.aspx on your pageload
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim CheckButton As String = Session("CheckButton")
Dim query As String
If (CheckButton = "Button1Clicked") Then
query = "SELECT * FROM Table1"
Else If (CheckButton = "Button2Clicked") Then
query = "SELECT * FROM Table2"
Else
Response.Write("<script>alert('Error!')</script>")
End If
SqlDataSource1.SelectCommand = query
SqlDataSource1.DataBind()
End Sub

creating event control in vb.net. Multiple controls with the same ID '1' were found

Im trying to create buttons on page load and have event controls to those. Im able to create the buttons but the event doesnt seem to be triggered when the button is clicked instead it throws an error stating multiple controls with id found.I think this has something to do with postback and unique ID creation for the buttons. can some one point me as to what to be added along with this?
Sub createbutton()
Dim but As New Button
but.Text = "save"
but.ID = "but"
AddHandler but.Click, AddressOf Button_Click
Me.form1.Controls.Add(but)
End Sub
The event control for this is as below.
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
' Handle your Button clicks here
MsgBox("done")
End Sub
Im getting the error
Multiple controls with the same ID '1' were found
The subroutine createbutton works on page load as follows.
Public Class Default3
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ' to gen page on load ;)
createbutton()
End Sub
Help is appreciated , Thanks :)
i think you are a guy who worked a lot with VB 6.0
Control array feature is available in VB 6.0
in VB.net everything is depend upon control ID.
if you don't have specific requirement like ID should be same then i suggest pls append prefix and incremental ID would resolve your issue.
Let me know if you have some specific requirements
Thanks
Asif
Corrected Code, Instead of ID it's name which allow uniqueness
Public Class Form1
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
' Handle your Button clicks here
MsgBox("done")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
createbutton()
End Sub
Sub createbutton()
Dim but As New Button
but.Text = "save"
but.Name = "but"
AddHandler but.Click, AddressOf Button_Click
Me.Controls.Add(but)
End Sub
End Class

Programmatically databind listview while using datapager

I have a listview and two data pagers. My listview is hooked up to a data source whose data is ordered randomly. ORDER BY NEWID()
As you can imagine, each time I select a page or click next/prev page all the data is randomized making the datapager quite useless.
I figured I could set the datasource when the page is not posted back and then programmatically set the datasource to the listview but now when selecting a page or clicking the next/prev buttons, the page just simply doesn't change..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim dv As DataView = sdsMembres.Select(DataSourceSelectArguments.Empty)
lvListMembres.DataSource = dv
lvListMembres.DataBind()
DataPager2.PagedControlID = "lvListMembres"
DataPager3.PagedControlID = "lvListMembres"
DataPager2.DataBind()
DataPager3.DataBind()
End If
End Sub
What am I missing / is there a better way to do this. The order by MUST be random and I MUST have the data pagers separate from the listview.
Thank you!
Take the code between the If statement and place it in a separate function.
Add a method of storing the data, in this particular case I'll store it as a DataTable in a session.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' Clear datatable from session
Session("CourtierList_dt") = Nothing
' Set datasource to listview and save in a session variable
SetCourtierList()
End If
End Sub
Protected Sub SetCourtierList()
Dim dt As DataTable
If Session("CourtierList_dt") Is Nothing Then
Dim dv As DataView = sdsMembres.Select(DataSourceSelectArguments.Empty)
Session("CourtierList_dt") = dv.ToTable
End If
dt = Session("CourtierList_dt")
lvListMembres.DataSource = dt
lvListMembres.DataBind()
DataPager2.PagedControlID = "lvListMembres"
DataPager3.PagedControlID = "lvListMembres"
DataPager2.DataBind()
DataPager3.DataBind()
End Sub
Also, make sure to add the PagePropertiesChanging event to the listview
Protected Sub lvListMembres_PagePropertiesChanging(sender As Object, e As System.Web.UI.WebControls.PagePropertiesChangingEventArgs) Handles lvListMembres.PagePropertiesChanging
DataPager2.SetPageProperties(e.StartRowIndex, e.MaximumRows, False)
DataPager3.SetPageProperties(e.StartRowIndex, e.MaximumRows, False)
SetCourtierList()
End Sub
And there you have it, hope this is helpful for someone.

Web Controls Not Talking to Each other in ASP.NET using VB.NET

I have an asp.net page that loads two controls, Control A and Control B. Control A has some generic form submit and clear buttons that trigger click events in its' own code behind which use reflection to call the update function in Control B which has a few input fields. I have debugged this and everything seems to be in order, however; when the update function in control B is called the input fields are not returning a value when using inputname.text or me.inputname.text. Does anyone have any ideas why this is not working? Any guidance would be appreciated.
This is the code in Control A's codebehind which calls the update method in Control B's code behind
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Try
Dim lctlControl = Session("SelectedQstnCtl")
Dim methodObj = lctlControl.GetType().GetMethod("UpdateGenInfo", BindingFlags.NonPublic Or BindingFlags.Instance)
' Execute UpdateGenInfo method to update the data
methodObj.Invoke(lctlControl, Nothing)
Catch ex As Exception
'TODO: check for concurrency error here
End Try
End Sub
This is the update function in Control B that is being called. The session values are being passed, but the form fields are not.
Protected Sub UpdateGenInfo()
Dim lclUtil As New clUtility
Dim genInfo As New clGenInfo
Try
Dim dt As Integer
'Update Data for 1-2
dt = genInfo.UpdateGenInfo_E1_01_02(Session("ConnStrEP"), Me.varLastUpdate, Session("AppNo"), Session("RevNo"), _
Me.txtPrName.Text, Me.txtPrAddr1.Text, Me.txtPrAddr2.Text, _
Me.txtPrCity.Text, Me.txtPrState.Text, Me.txtPrZip.Text)
Catch ex As Exception
'Display error
lclUtil.DisplayMsg(Me.lblErrMsg, String.Format("Error Location: Sub LoadGenInfo (ctlE1_01_02) {0}", ex.Message))
End Try
End Sub
The most likely cause is that the control instance stored in the session is not the control instance on the current page. For example, if you're storing the control instance in the session when the page is first loaded, and retrieving it on post-back, it will be a different instance.
If you can't give Control A a direct reference to Control B, then change your code to store the reference in the Page.Items collection:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Page.Items("SelectedQstnCtl") = TheSelectedQstnCtl
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Dim lctlControl = DirectCast(Page.Items("SelectedQstnCtl"), YourControlClass)
lctlControl.UpdateGenInfo()
End Sub
I see you are using reflection which might be an overkill for that task.Try referencing the method in the control directly.Make then method UpdateGenInfo public and then reference it like this.
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Try
Dim lctlControl = CType(Session("SelectedQstnCtl"),YourControlClass)
lctlControl.UpdateGenInfo()
Catch ex As Exception
End Sub
Public Function UpdateGenInfo()
'your code here
Catch ex As Exception
End Try
End Function
This way you can easily trace where your values are getting lost.Let me know how it goes.
Try yet another simple approach working demo here
In control a
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim testb1 = CType(Me.NamingContainer.FindControl("testb1"), testb)
testb1.UpdateGenInfo()
End Sub
In control b
Public Function UpdateGenInfo()
Try
Dim a = Me.TextBox1.Text
Catch ex As Exception
End Try
End Function
Aspx Parent Page
<uc1:testa ID="testa1" runat="server" />
<uc2:testb ID="testb1" runat="server" />
The controls in testb are in an update panel.Try this and let me know if this works.

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..

Resources