将字符串从表单传递到用户控件,错误对象引用要求非静态

本文关键字:对象引用 错误 静态 控件 用户 字符串 表单 | 更新日期: 2023-09-27 18:02:24

我正试图将字符串从表单传递到用户控件。我在这个网站上搜索,我发现了这个代码:

// form code
public string ID
{
    get { return username_txt.Text; }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
    EnrollFromMicrophone.ID = ID;
}
//user control code
 public string ID
{
    set { textBox2.Text = value; }
}

现在的问题是,我得到以下错误:

非静态字段、方法或属性"neurotec . samples . registrfrommicrophone . id"需要对象引用。集'

将字符串从表单传递到用户控件,错误对象引用要求非静态

正如错误消息已经提示的那样:您需要有一个对象实例来访问非静态字段。

代替:

EnrollFromMicrophone.ID = ID;
你需要

:

var enrollFromMicrophone = new EnrollFromMicrophone(); // or get the instance from somewhere
enrollFromMicrophone.ID = ID;

或者使属性为static:

public static string ID { get; set; }

然后在构造函数中使用它来设置textBox2.Text