Tuesday, May 16, 2017

Creating User Control in C#

 Hi in this tutorial I am going to show "How to Create Your own User Control"  and reuse it different windows form. So Lets Create a New Windows C# Project and name it as you like it.


Now Right Click on your project the Goto "Add->New Item.."


Select Windows Form from the left pane and the select usercontrol and name as wish.For this tutorial i am leaving default name(usercontrol1.cs)


Open Your User Control Designer and drag and drop label and textbox from the toolbox.



Go to your User Control Code behind by hitting "F7" from the designer and create a properties to access your textbox value.Paste the following code in Usercontrol Code behind.

public string sName
        {
            get
            {
                return textBox1.Text.ToString();
            }
            set
            {
                textBox1.Text = value;
            }
        }


Now to your Mainform where you want to use your user control and drag and drop the usercontrol from the toolbox.


Copy and Paste the Following code in the mainform Code Behind.

private void btnSubmit_Click(object sender, EventArgs e)
        {
            MessageBox.Show(userControl11.sName,"Information Message",MessageBoxButtons.OK);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            userControl11.sName = string.Empty;
        }

Output:



Download Source Code




No comments:

Post a Comment