VB.NET Programmatically add code between tags - vb.net

I have a custom control that does some work for me on async postbacks. Normally, I'd call the control directly from the presentation side using the following code on the ASPX page:
<mytag:CustomControl runat="server">
html (or other text) goes here
</mytag:CustomControl>
However, in my current application, I need to dymanically create the control from the codebehind, using code similar to the following:
Dim myControl As myClass.CustomControl = New myClass.CustomControl
myControl.ID = "someID"
myControl.?????? = "html (or other text) goes here"
Me.Controls.Add(myControl)
When adding the control to the page dynamically, how do I add info that would normally be between the start and end tags if the control were added the normal, non-dynamic way?
Thanks
Here's the actual control:
Protected Overloads Overrides Sub Render(ByVal writer As HtmlTextWriter)
Dim scriptmanagerPage As ScriptManager = ScriptManager.GetCurrent(Page)
If scriptmanagerPage Is Nothing Then
'Do nothing
Else
'See if we are in a postback
If scriptmanagerPage.IsInAsyncPostBack Then
'We are in a postback; register the script
Dim stringbuilderWorking As New StringBuilder()
MyBase.Render(New HtmlTextWriter(New StringWriter(stringbuilderWorking)))
Dim stringScript As String = stringbuilderWorking.ToString()
ScriptManager.RegisterStartupScript(Me, GetType(ScanWorkXAJAX), UniqueID, stringScript, False)
Else
'Not in a postback
MyBase.Render(writer)
End If 'In an async postback
End If 'Scriptmanager present
End Sub

What do you mean by data? More controls?
You can use
myControl.Controls.Add(childControlHere);
EDIT After question was clarified:
Add a literal control. i.e.
myControl.Controls.Add(new LiteralControl("<b>hello world</b><script type='text/javascript'>alert('hi');</script>"));

Do you mean FIND and append data to controls inside your dynamic control?
You can use the WebControl.FindControl method to find your control embedded in your custom control and then you can add data via its properties.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.findcontrol.aspx

That depends on the properties of the custom control you are using. You may have to bind to a template to display so that events will be fired, it really just depends on your specific control.

Was able to accomplish this using a literal control.
Code above plus:
Dim myLiteral As LiteralControl = New LiteralControl
myLiteral.ID = "myLiteral"
myLiteral.Text = "html (or some other text) goes here"
myControl.Controls.Add(myLiteral)

Related

VB.NET Call Sub of another form

I know, that there are many questions related to this, but still I cannot find a workable solution.
Usually, it would work like this: A form creates an instance of another form in it's container like this:
Dim PolInstIn As New SubForm1
Private Sub LoadDetail()
PolInstIn.TopLevel = False
PolInstIn.Name = "Sub From"
PolInstIn.FormBorderStyle = Windows.Forms.FormBorderStyle.None
PolInstIn.Dock = DockStyle.Fill
Me.GroupBox6.Controls.Add(PolInstIn)
PolInstIn.Show()
End Sub
Then it's easy to call a Public Sub from the sub form like this:
Call PolInstIn.MyPublicSubInSubForm1()
However, this doesn't work for me in this case. When I run MyPublicSubInSubForm1() it doesn't throw any error, but does no action. If I write a value to SubForm1 textbox and read it back, it reads, but I don't see it on the screen, so I suspect it is written to some other accidental instance.
I suspect it is because my parent form is also an instance of an form created in very similar way like SubForm1. Basically the ParentForm is a form loaded into tabPage and SubForm1 is a module loaded into ParentForm. It can exist in many copies (tabs).
Could you point to any simple solutions?
Regards,
Libor
I see this question got a lot of views, so here is an answer.
1) No visual response of child form (only results) - this could have happened if I created more then 1 instances of the form. The example is just an example, but if one use it (accidentally) this way, it may result in new definition of a child form every time (and consequent symptoms like the ones described). In practice, I split form loading from loading data into to the form (done by a public sub in that form).
2) If you want also a back reference (to i.e. parent grid form), define a Public ParentFormGrid as GridName (note ParentForm is a reserved name) and on loading a child form, set
PollInstIn.ParentFormGrid = Me
This way you can alway asccess the parent form, i.e. reload the grid when you save changes on a line edited in child form.
make Private Sub LoadDetail() to a public :
Public Sub LoadDetail()
It work on my project. Hopely its what you want
Dim PolInstIn As New SubForm1
Private Sub LoadDetail()
PolInstIn.Name = "Sub From"
PolInstIn.Show()
PolInstIn.TopLevel = False
PolInstIn.FormBorderStyle = Windows.Forms.FormBorderStyle.None
PolInstIn.Dock = DockStyle.Fill
PolInstIn.Update()
PolInstIn.Refresh()
Me.GroupBox6.Controls.Add(PolInstIn)
End Sub

Script Errors In VB

I am trying to stop those annoying Runtime Errors in VB. I am using a tabcontrol with a webbrowser item. I am trying to supress the errors. It does not return any errors but at runtime, it doesn't work. This is my code
CType(TabControl.SelectedTab.Controls.Item(0), WebBrowser).ScriptErrorsSuppressed = True
What am I doing wrong?
Your browser control may not be Item(0) on the page (it could be in a panel etc), so as an alternative (and safer method) you can use the Controls.Find method to search the selected tab and all child controls in order to find the Browser on that tab.
Something like this:
'assumes you have a control named WebBrowser1 on the first tab page etc
Dim browserControlName As String = String.Format("WebBrowser{0}", TabControl1.SelectedIndex + 1)
Dim browser As WebBrowser = CType(TabControl1.SelectedTab.Controls.Find(browserControlName, True).First, WebBrowser)
browser.ScriptErrorsSuppressed = True

How to access to the properties of an UserControl from code side?

make my own UserControl and I can aggregate new TabPages to a TabControl and then, inside of then TabPage, I add my own UserControl using the following code.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim TabX As New Windows.Forms.TabPage("Tab " & TabCount.ToString) '(ConfiguracionTabPage)
Dim MyControl As New ClientesEmpresa
MyControl.Name = "Control" & TabCount.ToString
If ClientesTabControl.TabPages.Count = 10 Then
ClientesTabControl.TabPages.RemoveAt(9)
End If
TabX.Controls.Add(MyControl)
TabX.Name = "Tab" & TabCount.ToString
TabX.Text = "Tab" & TabCount.ToString
MyControl.TitularLbl.Text = "Coca Cola"
Me.ClientesTabControl.TabPages.Insert(0, TabX)
Me.ClientesTabControl.SelectedIndex = 0
TabCount += 1
End Sub
My user control have several Labels, TextBox and TabPages(inside of a TabControl).
Now I want to change some properties dynamically from the source code, but I don't know how to access them.
The most similar theme that I found is this How to Acces of an User control in c#, but, as the title says, is in C#, how I can do it in VB.NET?
Sorry, I just notice that the Enter key post the comment. :(
Thanks for your feedback, I understand what are you saying but I missing something in the middle.
When I create the control in running time in the above code I can access easily to the properties of the created object, in this case my UserControl, but I don't understand how to reach the properties of a particular instance of that control from outside of Button_Click; ie. another button_click event(second button)
I was thinking to use something like
Dim ControlList As Windows.Forms.Control() = Me.ClientesTabControl.TabPages(0).Controls.Find("ModeloLbl", True)
or
ClientesTabControl.TabPages(0).Controls.OfType(Of AlarmasVehiculo)()
But I'm stuck here.
------------------------------------- 3th post ---------------
Thanks Steve, I was resolved using "Control.Find" and a For Each but your solution is easier.
There's any way to get the name of the selected tab or I must to create an Array when I create the New TabPage?, the idea is to update the text of the controls inside of the selected tab only when is selected by the user or every 5 seconds but just the in selected one.
Thanks.
To borrow M4N's answer from the C# question, and translate it to VB:
Cleanest way is to expose the desired properties as properties of your usercontrol, e.g:
Public Class MyUserControl
' expose the Text of the richtext control (read-only)
Public ReadOnly Property TextOfRichTextBox As String
Get
Return richTextBox.Text
End Get
End Property
' expose the Checked Property of a checkbox (read/write)
Public Property CheckBoxProperty As Boolean
Get
Return checkBox.Checked
End Get
Set (value As Boolean)
checkBox.Checked = value
End Set
End Property
'...
End Class
In this way you can control which properties you want to expose and whether they should be read/write or read-only. (of course you should use better names for the properties, depending on their meaning).
Another advantage of this approach is that it hides the internal implementation of your user control. Should you ever want to exchange your richtext control with a different one, you won't break the callers/users of your control.
To answer your second question, if you need to access your dynamically created controls, you can do so easily using their names, for instance:
Dim c As ClientesEmpresa= CType(Me.ClientesTabControl.TabPages("Tab1").Controls("Control1"), ClientesEmpresa)
c.CheckBoxProperty = True

Properties not passing to from in VB.NET custom control

I have a custom VB.NET control that I created that is working correctly in one program but not in another. The control has one button and one form. The form displays some data based on the settings in the control.
This is the use in both test projects:
With Me.MyControl1
'.Connection = gConn
.Server = "servername"
.DBName = "dbname"
.TableName = "table"
.FieldString = "list of fields"
.ReturnColumn = 0
.AllowMultiSelect = True
End With
This is how I am passing the settings to my form.
...this form is a part of the control
Public Sub New(ByVal cmsl As MyCustomControl)
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.Connection = cmsl.Connection
Me.ConnectionString = cmsl.ConnectionString
Me.Server = cmsl.Server
Me.DBname = cmsl.DBName
Me.TableName = cmsl.TableName
Me.FieldString = cmsl.FieldString
Me.FilterString = cmsl.FilterString
Me.AllowMultiSelect = cmsl.AllowMultiSelect
Me.AutoPopulate = cmsl.AutoPopulate
Me.ReturnColumn = cmsl.ReturnColumn
Me.SelectTop = cmsl.SelectTop
End Sub
In TestProject1 - the control is working as expected
In TestProject2 - the control is not sending any of the settings I set to the form
My control works fine when I debug with the UserControl TestContainer.
I am using VB.NET on VS2005.
This is all done on the same machine. Why would this work in one project and not another?
Seems like a reference error. please show us how the UserControl is integrated. The problem must come from there.
And are you talking about a custom control, or a UserControl ? (Not the same thing for me)
Try some breakpoints in the props, and also, try checking the references :). You might be working with a second usercontrol overlapping on the first one or something like that :).
In winforms the Designer sometimes goes weird.

detect event on IE from visio

Can i have a link between a button on an IE page and a visio event ? ( for example : changing the color of a shape just by a click on a button on the IE page)
Not really very easy unless you have access to the HTML content in IE as well, but you could use a VBA class which implements a "withevents" private variable to capture a reference to a particular element on the page, and which has an event handler to respond to browser-based events. Eg. in a class "clsHTML":
Private WithEvents el As MSHTML.HTMLInputElement
Public Sub SetElement(t As MSHTML.HTMLInputElement)
Set el = t
End Sub
Private Function el_onchange() As Boolean
Debug.Print "captured change: value = " & el.Value
End Function
In other code, create an instance of the class and call "SetElement" using a reference to an element on the page in IE:
Dim objHTML As clsHTML 'global variable
Sub TestEvents()
Dim IE As Object
'set up your IE reference....
Set objHTML = New clsHTML
objHTML.SetElement IE.document.getElementById("tester2")
Debug.Print "set capture"
End Sub
In this instance you're capturing the "change" event on a textbox, but other elements will expose different events....
Edit: I tested this in Excel, but I'm assuming something similar will also work in Visio.
Edit2: you would probably be much better off creating a form in Visio to handle this than sticking with automating IE.
yes you should check the get started documentation of jquery
html :
<button id="mybutton" />
<div id="myshape">blabla</div>
javascript :
$('#mybutton').click(function() {
$('#myshape').css('background-color', '#555555');
});