我在窗体上放了两个自定义控件,各有一个文本框,
现在想在自定义控件2中取得自定义控件1中的TEXT1的文本值写到自定义控件2中的TEXTBOX中去,有人说要通过委托,我是新手,请问该怎么写呢?自定义控件1namespace WindowsFormsApplication10
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public void ReadText1()
{
string a = this.textBox1.Text.ToString();
}
}
}自定义控件2
namespace WindowsFormsApplication10
{
public partial class UserControl2 : UserControl
{
public UserControl2()
{
InitializeComponent();
}
private void GetText1ToText2()
{
//想通过自定义控件1中的ReadText1()读取自定义控件1中的text1.text中的值填写到 text2中
//如果不通过自定义控件1中的ReadText1(),有什么方法能取得text1.text中的值呢?
}
}
}
现在想在自定义控件2中取得自定义控件1中的TEXT1的文本值写到自定义控件2中的TEXTBOX中去,有人说要通过委托,我是新手,请问该怎么写呢?自定义控件1namespace WindowsFormsApplication10
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public void ReadText1()
{
string a = this.textBox1.Text.ToString();
}
}
}自定义控件2
namespace WindowsFormsApplication10
{
public partial class UserControl2 : UserControl
{
public UserControl2()
{
InitializeComponent();
}
private void GetText1ToText2()
{
//想通过自定义控件1中的ReadText1()读取自定义控件1中的text1.text中的值填写到 text2中
//如果不通过自定义控件1中的ReadText1(),有什么方法能取得text1.text中的值呢?
}
}
}
public partial class UserControl2 : UserControl
{
public UserControl2()
{
InitializeComponent();
}
public UserControl1 user1; //定义一个自定义控件1
private void GetText1ToText2()
{
user1.ReadText1();
}
private void button2_Click(object sender, EventArgs e)
{
GetText1ToText2();会出现未将对象引用设置到对象的实例
}
请问为何会出现这个提示呢?
没有new UserControl1
或者没有传递UserControl1属性
所以就是null了
还真是,我改成了
user1 =new UserControl1();
user1.ReadText1();
就能读到自定义控件1中的Text1的值了。还想再问一下,那现在窗体上除了两个自定义控件之外,我再放一个textbox3,我怎么能取到这个textbox3的值呢? 实际上我是想知道在自定义控件中怎么去取父窗体上的别的对象,因为在我的实际问题中,我需要去取父窗体上的一个集合中的内容。
user1 =new UserControl1();
user1.ReadText1();
这种写法是只有当设计时Textbox1中就有值时才能读到。
如果TextBox1中原来为空,当程序运行后才在里面填写上字符,那么上面的代码就取不到TextBox1中相应的值。请大家帮我,我要怎么才能在 UserControl2中取到 UserControl1中的TextBox1里的值呢?(该值是程序运行后填写进去的,不是一开始就有)
我是新手,请问怎么写“实例化的公有方法”啊?
我要是在自定义控件2中定义一个自定义控件1,再取TEXT1的值,就会出现“未将对象引用设置到对象的实例”
我就是不知道怎么将它实例化。
本身的属性可能就是你自定义控件中其他控件的值了。比如说,你自定义控件中有TextBox,Label...
你定义属性tbxText是得到TextBox的值
属性lblText是得到Label的值
自定义控件1中写一个方法这样:
public string ReadText1()
{
string a = this.textBox1.Text.ToString();
return a;
}
自定义控件2按钮事件调用的方法:
private void GetText1ToText2()
{
textBox2.text= 自定义控件1.ReadText1();
}
button2可以直接获得,不需要再进行点击之类的其实就是两个窗体之间传递数据的问题
你需要在button1中声明一个委托变量,然后呢 在button2中去实现就ok了