0

I have two forms. On the first form I have a virtual numpad (I have a GroupBox and inside I have number buttons and this is my virtual numpad). With this virtual numpad I enter numbers into a TextBox. On the second form I have another TextBox where I enter numbers.

I want to use my virtual numpad on this second form. How can I do that?

If someone explained to me what I should do, step by step, I will be pleased.

Christoffer Lette
  • 14,346
  • 7
  • 50
  • 58
modest and cute girl
  • 785
  • 4
  • 13
  • 24

5 Answers5

2

1) Create a WinForms project, I called it "ReusingUserControlsSample"
2) Create a new UserControl, name it MyUserControlWithButtons or whatever else you like
3) Just out of habit, set "AutoSize=true" and AutoSizeMode="GrowAndShrink" on the UserControl properties. Later you may learn what they do
4) On the UserControlDesigner place some button on the control, name them "btnLetterA", "btnLetterB", "btnLetterC"
5) Double click on each of the buttons, so the click-handlers will be generated
6) In your UserControl's code, make a public TextBox TheOutput property
7) In your UserControl's code, in each of the click-handlers you've generated in step (5), add a line that adds some text to the TheOutput textbox's TextBox property. Remeber to check the TheOutput for NULL.

BUILD.

8) go back to Form1
9) Place MyUserControlWithButtons on the form, name it "mykeyboard"
10) Place a TextBox on the form, name it "mytextbox"
11) Go to the Form1's code
12) in te constructor, BELOW the "InitializeComponent", asign the mytextbox to the TheOutput of mykeyboard

And this is it. Now you can build it and run, and everything should be OK. Please not that whole code of the 'keyboard' is in the usercontrol. The form only has set it up to work with that textbox. On the second form you can do it in the same way: place keyboard, place textbox, setup the keyboard to write to that textbox and it will work the same.

The Code:

MyUserControlWithButtons.cs

using System;
using System.Windows.Forms;

namespace ReusingUserControlsSample
{
    public partial class MyUserControlWithButtons : UserControl
    {
        public MyUserControlWithButtons()
        {
            InitializeComponent();
        }

        public TextBox TheOutput { get; set; }

        private void btnLetterA_Click(object sender, EventArgs e)
        {
            TheOutput.Text += "A";
        }

        private void btnLetterB_Click(object sender, EventArgs e)
        {
            TheOutput.Text += "B";
        }

        private void btnLetterC_Click(object sender, EventArgs e)
        {
            TheOutput.Text += "C";
        }
    }
}

MyUserControlWithButtons.cs

namespace ReusingUserControlsSample
{
    partial class MyUserControlWithButtons
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnLetterA = new System.Windows.Forms.Button();
            this.btnLetterB = new System.Windows.Forms.Button();
            this.btnLetterC = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // btnLetterA
            // 
            this.btnLetterA.Location = new System.Drawing.Point(3, 3);
            this.btnLetterA.Name = "btnLetterA";
            this.btnLetterA.Size = new System.Drawing.Size(66, 21);
            this.btnLetterA.TabIndex = 0;
            this.btnLetterA.Text = "The \"A\"";
            this.btnLetterA.UseVisualStyleBackColor = true;
            this.btnLetterA.Click += new System.EventHandler(this.btnLetterA_Click);
            // 
            // btnLetterB
            // 
            this.btnLetterB.Location = new System.Drawing.Point(66, 30);
            this.btnLetterB.Name = "btnLetterB";
            this.btnLetterB.Size = new System.Drawing.Size(66, 21);
            this.btnLetterB.TabIndex = 0;
            this.btnLetterB.Text = "The \"B\"";
            this.btnLetterB.UseVisualStyleBackColor = true;
            this.btnLetterB.Click += new System.EventHandler(this.btnLetterB_Click);
            // 
            // btnLetterC
            // 
            this.btnLetterC.Location = new System.Drawing.Point(3, 57);
            this.btnLetterC.Name = "btnLetterC";
            this.btnLetterC.Size = new System.Drawing.Size(66, 21);
            this.btnLetterC.TabIndex = 0;
            this.btnLetterC.Text = "The \"C\"";
            this.btnLetterC.UseVisualStyleBackColor = true;
            this.btnLetterC.Click += new System.EventHandler(this.btnLetterC_Click);
            // 
            // MyUserControlWithButtons
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.AutoSize = true;
            this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.Controls.Add(this.btnLetterC);
            this.Controls.Add(this.btnLetterB);
            this.Controls.Add(this.btnLetterA);
            this.Name = "MyUserControlWithButtons";
            this.Size = new System.Drawing.Size(135, 81);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button btnLetterA;
        private System.Windows.Forms.Button btnLetterB;
        private System.Windows.Forms.Button btnLetterC;
    }
}

Form1.cs

using System.Windows.Forms;

namespace ReusingUserControlsSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            mykeyboard.TheOutput = mytextbox;
        }
    }
}

Form1.Designer.cs

namespace ReusingUserControlsSample
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.mytextbox = new System.Windows.Forms.TextBox();
            this.mykeyboard = new ReusingUserControlsSample.MyUserControlWithButtons();
            this.SuspendLayout();
            // 
            // mytextbox
            // 
            this.mytextbox.Location = new System.Drawing.Point(84, 38);
            this.mytextbox.Name = "mytextbox";
            this.mytextbox.Size = new System.Drawing.Size(100, 20);
            this.mytextbox.TabIndex = 0;
            // 
            // mykeyboard
            // 
            this.mykeyboard.AutoSize = true;
            this.mykeyboard.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.mykeyboard.Location = new System.Drawing.Point(66, 122);
            this.mykeyboard.Name = "mykeyboard";
            this.mykeyboard.Size = new System.Drawing.Size(135, 81);
            this.mykeyboard.TabIndex = 1;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 264);
            this.Controls.Add(this.mykeyboard);
            this.Controls.Add(this.mytextbox);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox mytextbox;
        private MyUserControlWithButtons mykeyboard;
    }
}

Program.cs

using System;
using System.Windows.Forms;

namespace ReusingUserControlsSample
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
  • Yuppi Yuppi it worked. now i had the chance to try all the things you said. i did step by step as you said. ( you helped me with the codes like MyUserControlWithButtons.cs and Form1.cs and etc... so thank you for being very explanatory and sending the codes to check also) i hope your tutorial gives a road-map to all newbies like me. and i hope people who will search about this usercontrol stuff, will benefit from your tutorial. – modest and cute girl Aug 14 '12 at 12:17
  • just two little Question: -how can i make this usercontrol component stay on vstudio for always or how can i this component to my other solutions? because this component goes from the toolbox when i open an another new solution. Question: - lets say i want to restrict the number of characters that the user can enter to the textbox or will make other specializations or limitations. Where will i code this? in the Form1.cs or in the MyUserControlWithButtons.cs ? thanks. – modest and cute girl Aug 14 '12 at 12:18
  • 1) One you "build" your project, your new component is packed into the resulting .EXE/.DLL file(s) that are created during the build. Whether it is an .exe or a .dll it depends on the project type. Usually, an "Application" proejct gives .exe,and a "class library" gives a .dll. Once you create a new solution/project,other "old" projects are forgotten. However,you may "Add reference" to them - just right click on your new the project,choose add reference, then **BROWSE** and point out the .EXE/.DLL file that you have built back then. After that, and after rebuilding, the control should show up. – quetzalcoatl Aug 14 '12 at 12:39
  • If it showed up, it will still show up only for that project that had "AddReference"d to it. However, if you like your new control very much, you may even register it in the VisualStudio, so it will be shown all the times, see http://stackoverflow.com/questions/4564576/how-do-i-add-a-user-control-to-toolbox and http://dhavalupadhyaya.wordpress.com/2008/07/20/how-to-add-custom-control-in-visual-studio-toolbox/ for starters. You still need the control to be sitting in a DLL or EXE. Or, also, you can add the original project to the same solution and set the reference to the project. – quetzalcoatl Aug 14 '12 at 12:42
  • 2) It strongly depends on what actually you want to achieve. Putting it in the Forms will mean that Form1 and Form2 will be able to have **different*8 restrictions. By putting it into the control, you will have to write it only once, but the restrictions will be reused and will be completely 100% the same. – quetzalcoatl Aug 14 '12 at 12:44
  • Great! respect the knowledge.nothing to say more. great effort and cristal nice explanatory tutorial. – modest and cute girl Aug 14 '12 at 12:46
1

Create a UserControl and place your virtual number pad groupbox/buttons on that. Then plce your new usercontrol on each form in place of the existing groupbox/buttons.

Sam Axe
  • 33,313
  • 9
  • 55
  • 89
  • i already tried to make a user control and add to my toolbox and tried to use it but when i couldnt manage it. fist i add custon control item to my solution then i drag and drop a groupbbox into the costumcontrol1.cs[Design] then i drag and drop a buttons inside the costumcontrol1.cs[Design] (since i have buttons inside my group box) andthen i built it. and i saw the componnt on my toolbox menu but when i drag and drop that didnt worked. (the problem was i didnt write any code and dont even write what into the costomcontrol1.cs. – modest and cute girl Aug 10 '12 at 23:10
  • my virtual numpad works perfect with one form but i want to use it on the other form also since i am making the same job there) if someone enlight i will be happy. didnt understand much from the document. thats why i asked about the steps. – modest and cute girl Aug 10 '12 at 23:14
  • thanks for trying to help. Quetzalcoatl put a hard work and made a documented tutorial if you want you can also look his tutorial. i thank you all for putting effort and trying to help. – modest and cute girl Aug 14 '12 at 12:23
1

You have two options:

  • either create a UserControl named "VirtualKeypad", and move your GroupBox and keypad buttons there, and then use(place) the new "VirtualKeypad" control on both of the forms,. Your control would have to expose some events, or have a property that would tell it which textbox to put the text at, etc..

  • or, if you want to have only one keypad, your are in trouble. The keypad must be one, but how your keypad buttons will know where to place the text entered? You will have to listen to focus changes, so that when you click/touch a textbox (first or second), and then click/touch the keypad, the keypad will have to check who had the focus before him (was the old focus on textbox first or second) and then put the digit/letter there. It will a little tricky to do.. Also, if you are a beginner in WinForms, you may have some problems with communication between two separate windows. I'd recommend you try with the UserControl first.

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
  • i already tried to make a user control and add to my toolbox and tried to use it but when i couldnt manage it. fist i add custon control item to my solution then i drag and drop a groupbbox into the costumcontrol1.cs[Design] then i drag and drop a buttons inside the costumcontrol1.cs[Design] (since i have buttons inside my group box) andthen i built it. and i saw the componnt on my toolbox menu but when i drag and drop that didnt worked. (the problem was i didnt write any code and dont even write what into the costomcontrol1.cs. – modest and cute girl Aug 10 '12 at 23:14
  • my virtual numpad works perfect with one form but i want to use it on the other form also since i am making the same job there) if someone enlight i will be happy. didnt understand much from the document. thats why i asked about the steps. – modest and cute girl Aug 10 '12 at 23:14
1

I would recommend just copying it over (preferably by copying it all into a new usercontrol, like Dan-o said, then just placing on on each form), and then swapping which is visible. To directly answer your question, though, you can move controls between forms by just modifying their Controls collection:

//FormA
FormB formBInstance;
void button_OnClick(object sender, EventArgs e){
    Controls.Remove(myControl);
    formBInstance.Controls.Add(myControl);
}

But then you have the implicit difficulties of managing which form it's on at any given time and I'd recommend you never cross controls between forms like this unless you really need to (and if you think you do, there's normally an easier way).

Since you asked step-by-step, which no-one here can really do, heres an explaination of user controls which should help. After that, just select it from your toolbox like you would any other control and make on on each form. (and if you really need them to behave 'as one', setup something to toggle which is visible).

K893824
  • 1,279
  • 8
  • 21
  • i already tried to make a user control and add to my toolbox and tried to use it but when i couldnt manage it. fist i add custon control item to my solution then i drag and drop a groupbbox into the costumcontrol1.cs[Design] then i drag and drop a buttons inside the costumcontrol1.cs[Design] (since i have buttons inside my group box) andthen i built it. and i saw the componnt on my toolbox menu but when i drag and drop that didnt worked. (the problem was i didnt write any code and dont even write what into the costomcontrol1.cs. – modest and cute girl Aug 10 '12 at 23:11
  • my virtual numpad works perfect with one form but i want to use it on the other form also since i am making the same job there) if someone enlight i will be happy. didnt understand much from the document. thats why i asked about the steps. – modest and cute girl Aug 10 '12 at 23:13
  • Write all the code in the control that you'd normally have had in the form for it originally. You basically take the design (those controls, which you've done) and the code (the event handlers I assume you had on the form originally) and put that in the code behind for the control instead. Ensure you didn't leave any of the code from it behind on the form, since that doesn't copy when you copy the design. – K893824 Aug 10 '12 at 23:16
  • so i copy my original group box codes which is in the form1.cs and paste into the costomcontrol1.cs[Design] and then copy the codes which is inside the form1.cs[Design] and paste it into the costumcontrol1.cs[Design] again (under the first coppied codes? ) and then buit it? did i understand correct? if i understand wrong can u make a small demonstration with one group box and one button if its not to much. thanks. – modest and cute girl Aug 10 '12 at 23:28
  • I believe that is correct. The reason it didn't work was because you moved the _design_ (the groupbox, etc) over, but not the _behaviour_, the code in the regular '.cs' file (code-behind) that told that groupbox, textbox, etc what to do. – K893824 Aug 10 '12 at 23:35
  • thanks for trying to help. Quetzalcoatl put a hard work and made a documented tutorial if you want you can also look his tutorial. – modest and cute girl Aug 14 '12 at 12:22
1

That was the way! It didnt worked because the buttons were just sitting there and you've propably not written any code to handle the clicks in the new control. You have to move WHOLE groupbox/buttons to the control, all along WHOLE code that handles it: all eventhandlers, all formatters, etc, everything you did on the first form to have the keypad working - now must be moved to the UserControl.

But this is not end! Your keypad-handling code, when a button click occurs, adds a text to the textbox, right? Now, in your usercontrol, there will be no textbox.

Your new beautiful control has to abstract from the textbox. Ideally, it should assume that there will be any textbox at all, but lets skip that. In the code of your new usercontrol, place a new property similar to public TextBox MyOutputTextbox {get;set}. Now, lets act that property this is your textbox that will get all the text and fix your UserControl code accordingly. Then place your Control on the forms. Then make sure that BOTH of your Form's constructor ASSIGN the textbox to that property:

public Form1() {
    InitializeComponent();
    myKeyPadControl.MyOutputTextbox = txtFirstBox;
}

and it should work.

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
  • Creating a property of "TextBox" type is a bad style.. Ideally, it should be an event "NewTextEntered" or a string property "EnteredText" that your textbodes would "bind" to. I cannot however explain everything.. There are very good tutorials out there about creating custom controls. Try starting with MSDN samples or CodeProject articles! – quetzalcoatl Aug 10 '12 at 23:25
  • :( i think its too much high level thing. but will be really happy to learn the thinsg you said. do you know a good youtube tutorial or a document tutorial where its showed step by step and with screenshots? or there is no such video can you do a very small sample example for the newbies and publish it and give the link so that we can have it as a referance. if its not much and if its not so complicated for you. and if you dotn have much time at the moment can you make it in this weekends and publish and put it in here as a referance so when people searchs on goods they see ur doc or vid. thks – modest and cute girl Aug 10 '12 at 23:38
  • Here you go.. Step-by-step, with the most eay way to do what you want. It is not pretty, but is short, coherent, simple and works. The code should be clear, but also try to do the steps on your own. – quetzalcoatl Aug 11 '12 at 00:02
  • Yuppi Yuppi it worked. now i had the chance to try all the things you said. i did step by step as you said. ( you helped me with the codes like MyUserControlWithButtons.cs and Form1.cs and etc... so thank you for being very explanatory and sending the codes to check also) i hope your tutorial gives a road-map to all newbies like me. and i hope people who will search about this usercontrol stuff, will benefit from your tutorial. – modest and cute girl Aug 14 '12 at 12:17
  • just two little Question: -how can i make this usercontrol component stay on vstudio for always or how can i this component to my other solutions? because this component goes from the toolbox when i open an another new solution. Question: - lets say i want to restrict the number of characters that the user can enter to the textbox or will make other specializations or limitations. Where will i code this? in the Form1.cs or in the MyUserControlWithButtons.cs ? thanks. – modest and cute girl Aug 14 '12 at 12:18