programmatically add dynamic AJAX controls to an ASP page - asp.net

Is it possible to programmatically add dynamic AJAX controls to an ASP page?
Now I create Textbox, Listbox dynamically in Page_Init Event. I have a Hover Menu that only attaches to the first ListBox.
I need to add it to the loop that creates the other controls so that it will be available on each List box.
Here is some of my code...
Dim num As Integer = Session("lineNums") ' Determines how many text boxes need to be created based on carriage returns from textblock.
Dim MainContent As ContentPlaceHolder = CType(Page.Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)
Dim ph As PlaceHolder = DirectCast(MainContent.FindControl("PlaceHolder1"), PlaceHolder)
For I = 1 To num
Dim txtD As New TextBox
txtD.ID = "txtDEdit" & I.ToString("D2")
ph.Controls.Add(txtD)
Dim litCtrlD As New Literal
litCtrlD.ID = "litCtrlD" & I.ToString("D2")
litCtrlD.Text = "<br />"
ph.Controls.Add(litCtrlD)
txtD.Text = "ENGLISH"
Dim txtA As New TextBox
txtA.ID = "txtAEdit" & I.ToString("D2")
ph.Controls.Add(txtA)
Dim litCtrla As New Literal
litCtrla.ID = "litCtrla" & I.ToString("D2")
litCtrla.Text = "<br />"
ph.Controls.Add(litCtrla)
Dim txtE As New TextBox
txtE.ID = "txtEEdit" & I.ToString("D2")
ph.Controls.Add(txtE)
Dim litCtrlE As New Literal
litCtrlE.ID = "litCtrlE" & I.ToString("D2")
litCtrlE.Text = "<br />"
ph.Controls.Add(litCtrlE)
txtE.Text = "TRANSLATION"
Dim txtB As New TextBox
txtB.ID = "txtBEdit" & I.ToString("D2")
ph.Controls.Add(txtB)
AddHandler txtB.TextChanged, AddressOf txtBChanged
Dim litCtrl As New Literal
litCtrl.ID = "litCtrl" & I.ToString("D2")
ph.Controls.Add(litCtrl)
Dim lstF As New ListBox
lstF.ID = "lstFEdit" & I.ToString("D2")
ph.Controls.Add(lstF)
Dim litCtrlF As New Literal
litCtrlF.ID = "litCtrlF" & I.ToString("D2")
ph.Controls.Add(litCtrlF)
Dim lstG As New ListBox
lstG.ID = "lstGEdit" & I.ToString("D2")
ph.Controls.Add(lstG)
AddHandler lstG.SelectedIndexChanged, AddressOf lstGChanged
Dim litCtrlG As New Literal
litCtrlG.ID = "litCtrlG" & I.ToString("D2")
ph.Controls.Add(litCtrlG)
Next I
I need to add the Hover Menu somewhere in this code area.
Dim lstG As New ListBox
lstG.ID = "lstGEdit" & I.ToString("D2")
ph.Controls.Add(lstG)
AddHandler lstG.SelectedIndexChanged, AddressOf lstGChanged
Dim litCtrlG As New Literal
litCtrlG.ID = "litCtrlG" & I.ToString("D2")
ph.Controls.Add(litCtrlG)
Thanks forany help on this one.
EDIT: I have added the following code to the Page_Init Event to try and build the Hover menus but am getting an error as described below....
' ************************************
' Creating Hover
Dim hoverMenuExt As New AjaxControlToolkit.HoverMenuExtender
hoverMenuExt.ID = "hovExtEdit" & I.ToString("D2") **
ph.Controls.Add(hoverMenuExt)
Dim litHoverMenuExt As New Literal
litHoverMenuExt.ID = "litHoverMenuExt" & I.ToString("D2")
ph.Controls.Add(litHoverMenuExt)
** Line with error: Variable "hoverMenuExt.ID" is used before it has been assigned a value. A null reference exception could result at runtime.
Any ideas on this part?

FYI, this is a great link that shows how to dynamically add standard controls.
Click here.
This provides an in-depth review of the dynamic control too elaborate to detail here.

Related

Visual Basic ASP.NET 4 Request.Form()

this may sound like a silly question but i am learning Visual Basic ASP.NET 4 and i have been asked to create a DropDownList which obtains information from a table using SQL. I cant seem to pull the selected item from the dropdownlist and show it on the screen using Request.Form.
I have tried this..
Dim selItem As String = Request.Form("DDList")
Response.Write(selItem)
but this does not show anything on screen. Please help as i am struggling with this.
I have added my dropdownlist as follows:
<asp:DropDownList ID="DDList" runat="server" Width="201px">
</asp:DropDownList>
<asp:DropDownList ID="DDList2" runat="server" Width="145px">
</asp:DropDownList>
My Class/Function
Public Class sqlFunc
Public Shared Function tableData() As DataSet
Dim oraConnect As New OracleConnection
oraConnect.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.Connection = oraConnect
oraCommand.CommandType = Data.CommandType.Text
Dim lsSQL As String = ""
lsSQL = "SELECT code, description FROM ref_code WHERE domain = 'SPECIALTY'"
oraCommand.CommandText = lsSQL
Dim da As New OracleDataAdapter(oraCommand)
Dim ds As New DataSet
da.Fill(ds)
Return ds
End Function
What i am using on my .aspx.vb page;
Dim dsData1 As New DataSet
dsData1 = tableData()
DDList.DataSource = dsData1
DDList.DataValueField = "code"
DDList.DataTextField = "description"
DDList.DataBind()
DDList.Items.Insert(0, New ListItem(String.Empty, String.Empty))
DDList.SelectedIndex = 0
You don't need to get the selected value using Request.Form if you are using an asp:DropDown ASP.net control. All you have to do is:
Dim selItem As String = DDList.SelectedValue
Response.Write(selItem)
If you really want to use Request.Form, do it like this:
Dim selItem As String = Request.Form(DDList.ClientID)
Response.Write(selItem)
Also, make sure you have ViewState enabled and that you do not rebind the DropDown at PageLoad when there is a PostBack:
Sub Page_Load
If Not IsPostBack
' Bind your DropDown here
End If
End Sub

Adding linebreak in loop

I use the following code to add smoe fileupload controls on my page. I'd like a line break between each one, but am having trouble getting it to work.
For i As Integer = 1 To 2
Dim fileupload As FileUpload = New FileUpload
fileupload.ID = "FileUp" & i
placeUpload.Controls.Add(fileupload)
Next
Thanks
For i As Integer = 1 To 2
Dim fileupload As FileUpload = New FileUpload
fileupload.ID = "FileUp" & i
placeUpload.Controls.Add(fileupload)
placeUpload.Controls.Add( new LiteralControl("<br />") )
Next

Programatically created ASP.NET TextBox retains Text value after PostBack even if Control is cleared

I have a drop down menu, and based on which item is selected, I call a web service and then dynamically create some text boxes.
The first time I drop down the menu and select an item, it works perfectly, and the text boxes are created and populated dynamically. However, the next time I drop down the menu (after the first postback), and select something different... after the second postback, the original values remain in the textboxes.
I am clearing all of the text boxes out of the placeholder, then re-creating them, and then setting a NEW value, how can they retain the OLD values... especially if I controls.clear them from the page?
Note: The second time they are being created, the textbox IDs DO end up being the same. Could that have something to do with it? This duplicate ID functionality will need to be supported.
My code, called from Page_Load, is as follows: (edited to add more code)
Private Sub RefreshEntity()
Dim XmlRecords As New XmlDocument
Dim XmlRecordsNode As XmlNode
Dim EntityType As String = EntityTypes.SelectedValue
Dim Entity As String = RecordValue.Value
Dim FieldName As String
Dim FieldValue As String
FieldPlaceHolder.Controls.Clear()
If RecordList.SelectedValue <> "Select..." Then
Try
XmlRecordsNode = LoginInfo.SharePointConnectWebService.GetMetaData(LoginInfo.WSUser, LoginInfo.WSPass, _
EntityType, Entity)
XmlRecords.LoadXml(XmlRecordsNode.OuterXml)
Catch ex As Exception
ConfirmLabel.Text = "<b>Error:</b><br>" & ex.Message.ToString
Return
End Try
Else
SetProperties.Visible = False
Return
End If
For Each OneNode As XmlNode In XmlRecords.SelectNodes("Fields").Item(0).ChildNodes
FieldName = OneNode.Name
FieldValue = OneNode.InnerText
Dim newLabel As Label = New Label()
newLabel.Text = FieldName & ": "
Dim newTextBox As TextBox = New TextBox()
newTextBox.ID = "Field-" & FieldName
newTextBox.Text = FieldValue
Dim newLine As Label = New Label()
newLine.Text = "<br><br>"
FieldPlaceHolder.Controls.Add(newLabel)
FieldPlaceHolder.Controls.Add(newTextBox)
FieldPlaceHolder.Controls.Add(newLine)
Next
SetProperties.Visible = True
End Sub
And the RecordValue.Value is a hidden field that gets populated in every Page_Load:
RecordValue.Value = RecordList.SelectedValue
Where RecordList is my DropDown menu.
This is likely due to ViewState or the Posted values clobbering your values.
Once a control is dynamically added to the controls collection it needs to catch up with all the page life cycle events that have already fired. In the case of a post back this means that the ViewState and/or the posted form value will clobber the .text property on the TextBox based on the order you're adding the dynamic controls to the controls collection and setting the .text property.
To fix this you can disable ViewState by setting the .EnableViewState property to false on the dynamically generate controls also add the controls to the controls collection before you set any properties on them.
For Each OneNode As XmlNode In XmlRecords.SelectNodes("Fields").Item(0).ChildNodes
FieldName = OneNode.Name
FieldValue = OneNode.InnerText
Dim newLabel As Label = New Label()
Dim newTextBox As TextBox = New TextBox()
Dim newLine As Label = New Label()
newTextBox.ID = "Field-" & FieldName
newLabel.EnableViewState = False
newTextBox.EnableViewState = False
newLine.EnableViewState = False
FieldPlaceHolder.Controls.Add(newLabel)
FieldPlaceHolder.Controls.Add(newTextBox)
FieldPlaceHolder.Controls.Add(newLine)
newLabel.Text = FieldName & ": "
newTextBox.Text = FieldValue
newLine.Text = "<br><br>"
Next
You're not storing the value in a Session variable and then putting it back into the text box later in your code?

How to generate asp.net textbox accoring to the digit displays in label text?

If in the label the default text is 10 then ten textbox controls will be generated in webform ...
Can anybody did this in VB.NET ?
Look at add control.
You simply use a loop based on the counter in the label then you say myWebForm.Controls.Add(txtBox); where txtBox is:
Dim txtBox as TextBox
Sure here is some code:
Dim count as Integer
count = CType(Me.myLabel.Text, Integer)
For i as Integer=0 to count-1
txtBox = new TextBox()
txtBox.ID = "txt" & i.ToString()
myForm.Controls.Add(txtBox)
Next i

How do I use id's of HTML elements in another sub when they are created from server-side code?

I have a table that I'm creating in code behind with the final column containing a HTML checkbox with runat="server".
The code I'm using to do this is:
Do While reader.HasRows
Do While reader.Read
Dim tNewRow As New HtmlTableRow
Dim cellSKU, cellDESCR, cellDept1, cellDeptGrp1, cellDeptRng1, cellStand, cellBoard, cellSelect As New HtmlTableCell
cellSKU.InnerHtml = "<a href='edit.aspx?edit=" & reader("SKUN") & "'>" & reader("SKUN") & "</a>"
cellDESCR.InnerText = reader("DESCR")
cellDept1.InnerText = reader("DPT1")
cellDeptGrp1.InnerText = reader("GRP1")
cellDeptRng1.InnerText = reader("RNG1")
cellBoard.InnerText = reader("BOARD")
cellStand.InnerText = reader("STAND")
cellSelect.InnerHtml = "<input type='checkbox' id='selectedSKU' value='" & reader("SKUN") & "' runat='server' />"
tNewRow.Cells.Add(cellSKU)
tNewRow.Cells.Add(cellDESCR)
tNewRow.Cells.Add(cellDept1)
tNewRow.Cells.Add(cellDeptGrp1)
tNewRow.Cells.Add(cellDeptRng1)
tNewRow.Cells.Add(cellStand)
tNewRow.Cells.Add(cellBoard)
tNewRow.Cells.Add(cellSelect)
tNewRow.Style.Add("border", "solid 1px #cccccc")
skusTable.Rows.Add(tNewRow)
Loop
reader.NextResult()
Loop
But I want to use the checkbox in another sub such as:
Protected Sub editSkus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles editSkus.Click
End Sub
Though I can't use selectedSKU.whatever as the checkbox doesn't exist on the page until the other section of code is run.
Is there a way I can get around this or another way of doing things?
Thanks in advance for any help.
It's nasty, but here goes...
Dim skusTable As New HtmlTable
Dim i As Integer
Do While reader.HasRows
Do While reader.Read
i = i + 1
Dim tNewRow As New HtmlTableRow
tNewRow.ID = "MyRow" & i
Dim cellSKU, cellDESCR, cellDept1, cellDeptGrp1, cellDeptRng1, cellStand, cellBoard, cellSelect As New HtmlTableCell
cellSKU.InnerHtml = "<a href='edit.aspx?edit=" & reader("SKUN") & "'>" & reader("SKUN") & "</a>"
cellDESCR.InnerText = reader("DESCR")
cellDept1.InnerText = reader("DPT1")
cellDeptGrp1.InnerText = reader("GRP1")
cellDeptRng1.InnerText = reader("RNG1")
cellBoard.InnerText = reader("BOARD")
cellStand.InnerText = reader("STAND")
'Create the checkbox as a webcontrol and add it to the table cell
Dim checkBox As New HtmlControls.HtmlInputCheckBox
checkBox.Value = reader("SKUN")
checkBox.ID = "selectedSKU"
cellSelect.ID = "SelectedCell"
cellSelect.Controls.Add(New WebControls.CheckBox)
tNewRow.Cells.Add(cellSKU)
tNewRow.Cells.Add(cellDESCR)
tNewRow.Cells.Add(cellDept1)
tNewRow.Cells.Add(cellDeptGrp1)
tNewRow.Cells.Add(cellDeptRng1)
tNewRow.Cells.Add(cellStand)
tNewRow.Cells.Add(cellBoard)
tNewRow.Cells.Add(cellSelect)
tNewRow.Style.Add("border", "solid 1px #cccccc")
skusTable.Rows.Add(tNewRow)
Loop
reader.NextResult()
Loop
Now all you need do is use FindControls to get to the element...
Dim myRow As HtmlControls.HtmlTableRow = skusTable.FindControl("MyRow" & i)
'Probably be good to check the object exists first....
If Not myRow Is Nothing Then
Dim myCell As HtmlControls.HtmlTableCell = myRow.FindControl("SelectedCell")
If Not myCell Is Nothing Then
Dim myCheckbox As HtmlControls.HtmlInputCheckBox = myCell.FindControl("selectedSKU")
If Not myCheckbox Is Nothing Then
'Got it! now is it selected?
Return myCheckbox.Checked
End If
End If
End If
The runat="Server" attribute is parsed by the ASP.NET process and indicates that it should create some kind of control object. At the point your code is running this parsing has already been done. ASP.NET does not parse content added to the InnerHTML property to look for additional runat attributes or any other ASP.NET specific markup, InnerHTML is expected to be strictly standard HTML that is to be sent to the server.
You could create an instance of the CheckBox ASP.NET control and add it to the cellSelect controls collection, which is the equivalent to runat="Server". However that doesn't really help because you want to bind an event to this control but on post back this control will no longer exist.
Is there a reason you are not using DataGrid to acheive this UI?

Resources