本文介绍了在用户控件之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在winForm中的两个用户控件之间传递数据?

例如,如果我有两个名为ucA和ucB的用户控件.
ucA包含一个文本框和一个按钮.
ucB包含一个标签,单击该按钮时,文本框中的文本应显示在ucB的标签中.

在此先感谢C#newbee. :)

How do I pass data between two usercontrols in a winForm?

For example if I have two usercontrols named ucA and ucB.
ucA contains one textbox and one button.
ucB contains a label, and when clicking the button the text in the textbox should appear in the label in ucB.

Thanks in advance from a C# newbee. :)

推荐答案

using System.Drawing;
using System.Windows.Forms;

namespace UserControlInteraction
{
    public partial class Form1 : Form
    {
        private UCA ucA;
        private UCB ucB;

        public Form1()
        {
            InitializeComponent();
            ucA = new UCA();
            ucA.Size = new Size(150, 50);
            ucB = new UCB();
            ucB.Location = new Point(0, 50);
            Controls.AddRange(new Control[] { ucA, ucB });
            ucA.UpdateText += new EventHandler<TextEventArgs>(ucA_UpdateText);
        }

        void ucA_UpdateText(object sender, TextEventArgs e)
        {
            ucB.LabelText = e.Text;
        }
    }

    public class UCA : UserControl
    {
        public event EventHandler<TextEventArgs> UpdateText;

        private TextBox textBox;
        private Button button;

        public UCA()
        {
            textBox = new TextBox();
            textBox.Location = new Point(0, 0);
            button = new Button();
            button.Location = new Point(0, 24);
            button.Text = "&Update";
            button.Click += new EventHandler(button_Click);
            Controls.AddRange(new Control[] { textBox, button });
        }

        private void button_Click(object sender, EventArgs e)
        {
            OnUpdateText(new TextEventArgs(textBox.Text));
        }

        protected virtual void OnUpdateText(TextEventArgs e)
        {
            EventHandler<TextEventArgs> eh = UpdateText;
            if (eh != null)
                eh(this, e);
        }
    }

    public class UCB : UserControl
    {
        private Label label;

        public UCB()
        {
            label = new Label();
            label.Size = new Size(100, 13);
            Controls.Add(label);
        }

        public string LabelText
        {
            get { return label.Text; }
            set { label.Text = value; }
        }
    }

    public class TextEventArgs : EventArgs
    {
        private string text;

        public TextEventArgs(string text)
        {
            this.text = text;
        }

        public string Text
        {
            get { return text; }
        }
    }
}



这篇关于在用户控件之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 01:02