Windows 窗体应用程序中的用户控件 [英] User control in windows forms application

查看:41
本文介绍了Windows 窗体应用程序中的用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有文本框和标签的简单用户控件.当我以另一种形式使用用户控件时,我创建了公共属性来访问文本框中的文本.

I have a simple user control with a text box and label in it. I created public properties to access the text in the textbox when I use the user control in another form.

我的问题是当我在表单中调用它时,该属性返回空值.我错过了什么吗?

My problem is the property is returning null value when I call it in the form. Am i missing anything?

我的属性如下::

 public partial class UserControl1 : UserControl
 {
        public UserControl1()
        {
            InitializeComponent();
        }

        public string rtnTxtMake
        {  
            get 
            { 
                return txtMake.Text; 
            }
            set 
            { 
                txtMake.Text = value; 
            } 
        }
 }

在下一个表单按钮点击事件中,我调用该属性如下

and in the next forms button click event i call the property as follows

        UserControl1 Usc = new UserControl1();
        string Make = Usc.rtnTxtMake;

        MessageBox.Show(Make)

推荐答案

UserControl1 Usc = new UserControl1();
string Make = Usc.rtnTxtMake;

如果您的用户控件默认有一个空文本框字段,那么上面两行代码将返回 nullString.Empty 似乎是正确的(检查通过 String.IsNullOrEmpty),因为您显式地创建了用户控件的新实例.

If your user control has by default an empty textbox field, then it seems correct that the above two lines of code would return either null or String.Empty (check via String.IsNullOrEmpty), since you explicitly create a new instance of your user control.

我想你真正想要的是这个:

I suppose what you really want is this:

  • 您已将用户控件插入到设计器的表单中.我们称这个用户控件实例为 ctlUser.

您有一个带有 Click 事件处理程序的按钮.您问题中的最后几行代码来自该处理程序方法.

You have a button with a Click event handler. The last few lines of code in your question are from that handler method.

在处理程序中,您不会创建用户控件的新实例 (Usc),而是引用您之前插入到表单中的那个,ctlUser.那么事情应该会按预期进行.

In the handler, you wouldn't create a new instance of your user control (Usc) but refer to the one that you previously inserted into your form, ctlUser. Then things should work as expected.

这篇关于Windows 窗体应用程序中的用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆