• 0

[VB.NET] Copy a control?


Question

I need to know how to copy a control in Visual Basic .net. Basically I want to take a control, snapshot it in time, and then make it visible. Ideally I'd like to do this with a panel of some sort. If I am unclear but you think you can help just let me know what else you need to know.

I've been reading that it is possible through reflection, but I cannot find any good examples of how to do it with reflection. Thanks.

Link to comment
https://www.neowin.net/forum/topic/568557-vbnet-copy-a-control/
Share on other sites

14 answers to this question

Recommended Posts

  • 0

Are you trying to clone an object? For example say you have a textbox and you want to make a copy of it so you have two different ones? I think thats what you mean. If so, you can do this through serializing. Look here for an example: http://discuss.joelonsoftware.com/default....net.12.301381.5

  • 0

I will read through that article...

...basically I want to say like if you type some text into that text box, click a button, and a new text box appears there with the exact text you had in it. That's not my end goal here because that would be incredibly easy to do, but I think for the purposes of an exercise that would be pretty simple.

  • 0

Ok read through the article and it doesn't seem to work on forms/controls for some reason. I made a blank control that I can stick on my form and when I insert it into the form it works, but when I try to copy it it says that it is not marked as Serializable. I did add "<Serializable()>" before the Public Class declaration but I guess it needs to be somewhere else?

  • 0

You just want to have a textbox on a page, you type in something into it, hit a button, and the other textbox shows up with the text in it?

Simple.

Create a textbox, and a panel with a textbox in it. Or you can do it dynamically in the code as well.

Once you hit the button, make the panel visible, and just assign the textbox in the panel with the text from the other textbox.

You probably don't even need the panel.

  • 0
  LRoling said:
You just want to have a textbox on a page, you type in something into it, hit a button, and the other textbox shows up with the text in it?

Simple.

Create a textbox, and a panel with a textbox in it. Or you can do it dynamically in the code as well.

Once you hit the button, make the panel visible, and just assign the textbox in the panel with the text from the other textbox.

You probably don't even need the panel.

No I wanted to do this with something very complex - like say a control with a lot of dynamic stuff including a browser, text boxes, check boxes, and more. User modifies it, presses a button and now you have 2 identicle forms with identicle content and appearance.

It's simple to just create a new text box but not so easy to duplicate other things. I figured a text box would be a good example to try to "clone" though because it is simple. I mean I don't want to make a new one and copy over stuff to it; I want to make an exact copy of it.

I did manage to figure out how to do it in C# but it doesn't copy over all of the control's attributes and it doesn't work that great. Still looking for something in visual basic.

  • 0
  JiveMasterT said:
No I wanted to do this with something very complex - like say a control with a lot of dynamic stuff including a browser, text boxes, check boxes, and more. User modifies it, presses a button and now you have 2 identicle forms with identicle content and appearance.

It's simple to just create a new text box but not so easy to duplicate other things. I figured a text box would be a good example to try to "clone" though because it is simple. I mean I don't want to make a new one and copy over stuff to it; I want to make an exact copy of it.

What do you think cloning is? You have to create a new instance of something and copy the source attributes you want. Extend your controls to support ICloneable and implement your own cloning method. Or, you can extend TextBox to include a copy constructor and do the same as ICloneable. Cloning is not the same instance. It is a copy of something, and you'll have to do the work. ;)

You can simplify the process by using reflection.

http://blogs.msdn.com/irenak/archive/2006/05/09/593555.aspx

It's in C# but is translatable to VB.NET fairly easily. Personally, I'd genericize the process described in that article by creating a generic interface that you can implement in the controls you want to clone.

  • 0

Right, i know kinda what you wanna do, and had this same issue a while back..

(And btw, i have no idea about C#, so... generalising that this guy knows C# to port to VB.Net is obscure but hey, w/e)

The below code would be for generating a Label on run-time.

Dim myLabel as Label
myLabel = new Label()
myLabel.width = 30
myLabel.height = 15
myLabel.left = 0
myLabel.top = 0
myLabel.name = "Label1"
Me.Controls.Add(myLabel)

That would generate a label with those properties, and can be used on button press or whatever.

I'm sure the same would work for forms, textboxes, ect.

Could get rather code heavy to generate a full form mind you :|

  • 0

They have converters online, it'd be rather simple to cut and paste the code in. Some of them are amazingly accurate.

What MiG suggested was what I was thinking you could do, but you could even set the widths, etc. right off the other Label control. But I didn't think you wanted to do such an intensive process. If the form gets large, it'll be a tough one. Mind you, you can also have it all programmatically done on the click event.

Loop through all controls on the page that are made, then use an IF statement or CASE to determine each type for each control, and then make a new control based on the old one's type. So if it is looping through and it finds there is a Textbox, it creates a textbox, label creates label, etc.

  • 0
  LRoling said:
I am baffled by what the heck you are trying to do.

You want to create a bunch of controls, hit a button, and then the page duplicates the controls?

Pretty much. Thta would be easy except for one detail - the copy must be identicle to the parent in that it retains all of its child controls, any text entered in the text boxes, etc etc. The forms are built dynamically so there is no telling what they might have in them. I need a good way to basically snapshot a control or a form in time and then duplicate it.

  LRoling said:
They have converters online, it'd be rather simple to cut and paste the code in. Some of them are amazingly accurate.

What MiG suggested was what I was thinking you could do, but you could even set the widths, etc. right off the other Label control. But I didn't think you wanted to do such an intensive process. If the form gets large, it'll be a tough one. Mind you, you can also have it all programmatically done on the click event.

Loop through all controls on the page that are made, then use an IF statement or CASE to determine each type for each control, and then make a new control based on the old one's type. So if it is looping through and it finds there is a Textbox, it creates a textbox, label creates label, etc.

I was using this C# to VB.Net converter for another example and it worked pretty good. The VB app didn't really work because the forms were all busted. If I can find what website it was I'll post it back up here.

It's funny most of the stuff I want to try is in C# but the whole application is already written in VB.net and converting the project to C# would take a whole lot of time that I don't have. If this isn't possible to do in a reasonable manner then I guess I'll just throw in the towel on it and figure out another way to get that same effect. The combinations could be endless so it would be impossible to loop through everything and duplicate it that way as the rate of success would probably vary from instance to instance and that would not be good. There is also the problem of read-only attributes on controls that I would need modified and so it gets even more complex.

I really thought that this would be a common thing that has been figured out already haha.

  • 0

Ok so I converted that C# code from before to Visual Basic. It didn't totally convert properly but I worked out the kinks. It works on most things pretty well. The only thing is doesn't do is retain the text that is in text boxes and stuff like that. It does not work with webbrowser objects either for some reason. I've attached my project file if anyone wants to toy with it and see if we can get it to retain text dynamically and also do other things like webbrowser objects. I might continue to work on it later on today.

The attachment is a 7zip file renamed with a .txt extension. Just rename it, extract it, and check out the code.

Control_Copy_Testing.7z.txtFetching info...

  • 0

I needed this functionality as well.. it seems odd that cloning a control isn't a simple, built-in thing.

I ended up with a different approach but does generally the same thing. It's a simple idea: Each time you want to copy your "template" control, set its properties to what you want for the copy, then use the control's Render method to render it to a HTML string. Then you can insert the HTML string, representing the copy, anywhere you want on the page.

This is a little routine to render a control to a HTML string:

public string RenderControl(Control ctrl) 
{
	StringBuilder sb = new StringBuilder();
	StringWriter tw = new StringWriter(sb);
	HtmlTextWriter hw = new HtmlTextWriter(tw);

	ctrl.RenderControl(hw);
	return sb.ToString();
}

Thanks go to http://blogs.x2line.com/al/articles/859.aspx

So 3 steps:

1. Set the properties of the "template" control.

2. Render it to a HTML string.

3. Insert the string somewhere on the page. You can do that 2 ways:

a) Add it to the InnerHTML of an existing control, or

b) Add it to a control collection using ParseControl(strYourHTMLString)

If you don't want the original "template" control to render, set its Visible property to False after you've made all the copies you want. Note that Visible must initially be True for the Render method to actually output something to your string.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Elon Musk once again claims Tesla robotaxis are coming soon by David Uzondu Image via Depositphotos.com Tesla's CEO, Elon Musk, has announced a tentative start date of June 22 for the company's long-awaited public robotaxi service. According to a post on his social media platform X, the initial launch will be in Austin, Texas. Musk added a significant condition, however, saying "We are being super paranoid about safety, so the date could shift." The service is expected to begin with just 10 to 20 Model Y SUVs operating within a limited area and with remote human supervision. He also mentioned a plan starting June 28 for new Teslas to drive themselves from the factory to a customer's home. This is a moment many are probably waiting for, though it comes with a heavy dose of skepticism. Musk has made grand promises about self-driving before. This robotaxi network brings to mind the bold claims from all the way back in 2019 when the company said a similar service would launch the following year. That evidently did not happen. Federal regulators also have their doubts. Last year, the National Highway Traffic Safety Administration criticized Tesla for making its "Full Self-Driving" feature sound more capable than it actually is, demanding the company align its marketing with reality. Tesla is also driving into a field that is no longer empty. Waymo, Google's sibling company, is already a major player, offering hundreds of thousands of paid rides per week across Phoenix, San Francisco, Los Angeles, and even Austin. The company is so far ahead that it has begun testing in Tokyo. But being ahead means Waymo is also the first to face certain dangers. For example, on the evening of June 8, a group of protesters in downtown Los Angeles summoned Waymo vehicles during a demonstration. When the vehicles arrived, they slashed the tires, smashed the windows, and spray-painted the cars before setting three of them on fire. Which raises a thorny question for Tesla: if you can summon a car with no one inside, can you summon it just to destroy it? It's one thing for protesters to stumble upon a robotaxi and vandalize it; it's another for someone to use the app to call a driverless car to a secluded spot for a planned attack. With public sentiment around Musk so divided, especially given his DOGE shenanigans and his recent face off with Donald Trump, that's not just a theoretical problem. We've already seen this hostility play out in attacks where people vandalize Teslas, carving swastikas into them and spray painting slogans like "Burn More Teslas" on walls.
    • This is actually quite useful. But why wouldn't they implement this in the local file system? The code is obviously all there now... maybe in 5 years.
    • The new "Story Cards" in the Software section are nice, but I wish they had the product icon included. I use this section to identify updates for software that I use regularly, and it's sometime difficult to identify the software without the product icon. Thanks for your consideration. pelaird
    • Mozilla really needed to focus on their core product for a while now. I will not mourn the death of pocket or AI garbage. One thing they don't do that I believe they should is advertise more, and not just to their core audience, especially their additional services. Let people know they actually exist.
    • Is this like tailscale?
  • Recent Achievements

    • Week One Done
      Food-Beverages-Nutrition earned a badge
      Week One Done
    • Week One Done
      Tech Dogs earned a badge
      Week One Done
    • Enthusiast
      computerdave91111 went up a rank
      Enthusiast
    • Week One Done
      Falisha Manpower earned a badge
      Week One Done
    • One Month Later
      elsa777 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      524
    2. 2
      ATLien_0
      271
    3. 3
      +Edouard
      199
    4. 4
      +FloatingFatMan
      196
    5. 5
      snowy owl
      138
  • Tell a friend

    Love Neowin? Tell a friend!