• 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

    • Helpwire doesn't support sound transfer.
    • Here's your first look at Raycast for Windows, now in beta by David Uzondu Last September, we reported that Raycast, the popular macOS command bar and launcher tool, was set to make its way to Windows in 2025. Since its launch in 2020, Raycast has quickly become the go-to app that people recommend for new Mac users due to its speed, UI, features, and plethora of extensions. People have been begging for a Windows build, and even a Linux one, for a long time. Now, the company has published a YouTube video showcasing the beta on a Microsoft Surface and explaining how you can get your hands on it today. It's all opened by pressing the default hotkey (Alt + Space). This gives you a central command bar to launch apps, run commands, and search for files. You get a lot of the core features right now, like a calculator that handles natural language queries, a full clipboard history manager, and tools for creating text snippets and quicklinks. For example, typing .pdf instantly filters for just PDF documents, and using a forward slash lets you navigate through folder paths directly. Once you find a file, pressing Ctrl + K opens a contextual action menu with options like "Show in File Explorer" or "Copy File." The included calculator is also a powerhouse, handling everything from basic math to natural language queries, like "time in Barcelona" or "days until August 12." The full clipboard history manager is a massive upgrade over the Windows default. It keeps a running log of everything you copy to your clipboard, including blocks of text, links, images, and files. You can open the clipboard history and search through every item you've copied. It also comes with a powerful filtering system. By pressing Ctrl + P, you can filter your history to show only text, images, links, or even just colors. Its Quick AI feature is also included and will be free for everyone during the beta period. That means you can ask it questions and get answers without needing a Pro subscription for now. Quick AI is built on a set of AI models, like GPT-4o mini, which maintains conversational context, allowing for natural follow-up questions, and you can browse your entire chat history. There's also an "AI search" feature, which is listed as coming soon. The most surprising part is the support for third-party extensions right out of the gate. Raycast built its reputation on an extensive library of integrations that connect it to services like Slack, YouTube, and GitHub. While some of these extensions are written for specific macOS features and are not compatible, many of the extensions are written in JavaScript, which means a huge number of them already work from day one on Windows. Image: @alvaniss1g on X As you can guess, the beta is not feature-complete. A lot of the heavy-hitting Pro features are still on the roadmap and are promised to be coming soon. This includes Cloud Sync to keep your settings consistent across machines, as well as the much-loved Raycast Notes feature. If you are a Pro user on Mac looking to switch, you may want to wait a little longer for full parity. Snippet expansion and calendar integration are also on the to-do list for future updates. Getting into the beta is a bit of a process. Access is being managed through a gradual rollout, with priority given to users who signed up for the waitlist announced last year. If you are on the list, you can expect to receive an email soon. And if you don't like the waitlist, your best bet is to find a friend who already has an invite code, as each invited user gets a few extra codes to share. Sorry, Linux users, but there is no word on your build at the moment, and we're not holding our breath.
    • We M$ and our 801 loved partner$ are having a data party !
    • Wise Disk Cleaner 11.2.4 by Razvan Serea Wise Disk Cleaner is a free disk utility designed to help you keep your disk clean by deleting any unnecessary files. Usually, these unnecessary, or junk files appear as a result of program's incomplete uninstalls, or Temporary Internet Files. It is best if these files are wiped out from time to time, since they may, at some point, use a considerable amount of space on your drives. Wise Disk Cleaner, with its intuitive and easy to use interface, helps you quickly wipe out all the junk files. Using the program is indeed easy. It also works fast when both scanning for files and deleting files. The new Wise Disk Cleaner has more advantages: improved performance, better interface and scans/cleans more thoroughly. Wise Disk Cleaner Free provides lifetime free update service and Unlimited Free technical support. The first Slimming System software Wise Disk Cleaner is the first system slimming tool, which will help you to remove Windows useless files that you don't need, such as Korean IME, Windows Sample music, videos, pictures, Installers and Uninstallers of Updates Patches etc. Wise Disk Cleaner 11.2.4 Build 844 changelog: Improved cleaning rules for WPS Office and Mozilla Firefox. Added cleaning support for Jetbrains Pycharm, Jetbrains WebStorm, Jitsi, Visual Studio Code, jv16 PowerTools, Kakao Talk, Kingo Root, Launchy, Layers of Fear, LBRY, League of Legends, Leapfrog Connect, and Leawo Prof Media. Fixed minor bugs from the previous version. Download: Wise Disk Cleaner 11.2.4 | 6.9 MB (Freeware) Download: Portable Wise Disk Cleaner 11.2.4 | 7.3 MB View: Wise Disk Cleaner Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Hi everyone! I’m looking for some help. I’m using HelpWire for remote support, and while everything else works fine, I’m not getting any sound from the remote computer. Is there a setting I might be missing? Any tips would be appreciated. Thanks in advance!
  • Recent Achievements

    • Conversation Starter
      Kavin25 earned a badge
      Conversation Starter
    • One Month Later
      Leonard grant earned a badge
      One Month Later
    • Week One Done
      pcdoctorsnet earned a badge
      Week One Done
    • Rising Star
      Phillip0web went up a rank
      Rising Star
    • One Month Later
      Epaminombas earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      537
    2. 2
      ATLien_0
      205
    3. 3
      +FloatingFatMan
      167
    4. 4
      Michael Scrip
      151
    5. 5
      Som
      127
  • Tell a friend

    Love Neowin? Tell a friend!