c# 非静态方法需要对象引用

本文关键字:对象引用 静态方法 | 更新日期: 2023-09-27 18:36:40

我想在静态方法中使用文本框中的文本,该方法显示 SQL 数据库中的列。我该怎么做?如果我执行下面的代码,我会遇到此错误:

非静态方法需要对象引用。

这是我的静态方法:

static void OnTagsReported(ImpinjReader sender, TagReport report)
        {
        SqlConnection Cn;
        SqlCommand Cmd;
        //SqlCommand Cmd1;
        Cn = new SqlConnection(@"Data Source=DESKTOP-    ODCFVR1'SQLEXPRESS;Initial Catalog=RFID;Integrated Security=True");
        Cn.Open();
         // This event handler is called asynchronously 
        // when tag reports are available.
        // Loop through each tag in the report 
        // and print the data.
        foreach (Tag tag in report)
        {
            MessageBox.Show ("voici l'antenne :"+ tag.AntennaPortNumber +", EPC :"+ tag.Epc);
            Cmd = new SqlCommand ("INSERT INTO EPC (Epc_CODE) values('" + tag.Epc + "')", Cn);
            Cmd.ExecuteNonQuery();
            SqlCommand Cmd1 = new SqlCommand();
            Cmd1.CommandText = " select * from Epc Where EPC_code = '" +     tag.Epc + "' ";
            Cmd1.Connection = Cn;
            String result = " ";
            Cmd1.ExecuteNonQuery();
            result = Cmd1.ExecuteScalar().ToString();
            textBox5.Text = result; // here is my problem

            Cn.Close();
        }
}

谢谢!

c# 非静态方法需要对象引用

您正在静态方法中引用实例成员。您可以:

  • return Cmd1.ExecuteScalar().ToString();并设置调用方法中的文本框文本
  • 或传递设置文本框文本的Action<string>委托
  • 使方法成为实例方法(删除static修饰符)

由于您的方法看起来像某种事件处理程序,因此我不会将其设置为静态。

摘要:必须删除对非静态成员(文本框)的访问权限或使方法成为非静态方法。