2016-02-28 44 views
1

我想在显示SQL数据库中的列的静态方法中使用文本框中的文本。我怎样才能做到这一点?如果我下面执行我的代码,我有这样的错误:c#非静态方法需要对象引用

An object reference is required for the non-static method.

这是我的静态方法:

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(); 
     } 

} 

谢谢!

+5

**警告**您的代码极易遭受SQL注入攻击。 –

+1

'textBox5'似乎是一个实例成员。从你的方法中删除静态。 –

回答

3

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

  • return Cmd1.ExecuteScalar().ToString();并设置呼叫methdo文本框中的文本
  • 或传递一个Action<string>委托其设置文本框的文本
  • 让你的方法的实例方法(删除static修改)

由于您的方法看起来像某种事件处理程序,我不会使它成为静态的。

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

+0

如果我让我的方法非静态的,我可以执行我的代码没有错误,但没有出现在文本框文本中。否则我是一个初学者在C#@ventiseis你能展示我怎么能应用前两种方法之一。 –

+0

你的问题不是静态方法。你的事件很简单,没有被调用 - 所以设置的东西似乎是错误的。我会建议你提供一个匹配的问题标题并提供更多的细节(你使用的是什么框架,涉及哪些硬件)。 *否则,你将不会得到有用的答案。*我们无法猜测你的环境。 – ventiseis

相关问题