B. Marwa
B. Marwa

Reputation: 19

c# An object reference is required for the non-static method

I want to use the text from a textbox in a static method that displays a column in my SQL Database. How can I do that? If I execute my code below, I have this error:

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

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

}

Thanks!

Upvotes: 1

Views: 783

Answers (1)

ventiseis
ventiseis

Reputation: 3099

You are referencing an instance member in a static method. You could either:

  • return Cmd1.ExecuteScalar().ToString(); and set the textbox text in the calling methdo
  • or pass an Action<string> delegate which sets the textbox text
  • make your method an instance method (remove the static modifier)

As your method looks like some sort of event handler, I wouldn't make it static.

Summary: You have to remove the access to nonstatic members (textbox) or make your method nonstatic.

Upvotes: 3

Related Questions