Calling method error

VAer-4038 771 Reputation points
2021-01-06T04:06:14.643+00:00

I have asked calling method before, and the thread gets messy (disorganized). Now I am starting a new thread with new issue.

I put public void InsertActivity() in public class GlobalMethod , which does not belong to any form.

In Form1, I try to call the method, but it does not recognize GlobalMethod.InsertActivity() ? What did I write wrong?

I don't really have programming knowledge, I am learning by doing. Feel like learning a lot in the past few days by solving one issue at a time.

Thanks.

    public class GlobalMethod  //It is just a class, not belong to any forms.
    {
        public static string Activity;
        public void InsertActivity()
        {
            OdbcConnection Cn = new OdbcConnection(GlobalVariables.DatabaseConnectionString);
            Cn.Open();            

            using (OdbcCommand cmd = new OdbcCommand("INSERT into [TableActivity](Username, EasternTime, Note) Values(@Username, @Time, @Note)", Cn))
            {
                DateTime dtLocal = DateTime.Now;
                TimeZoneInfo tziEST = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
                DateTime dtEastern = TimeZoneInfo.ConvertTime(dtLocal, tziEST);

                cmd.Parameters.Add("@Username", OdbcType.VarChar).Value = Environment.UserName;
                cmd.Parameters.Add("@Time", OdbcType.DateTime).Value = dtEastern;
                cmd.Parameters.Add("@Note", OdbcType.VarChar).Value = GlobalMethod.Activity;
            }
        }
    }


        private void Form1ButtonLogin_Click(object sender, EventArgs e)
        {
            GlobalMethod.Activity = "You log in.";
            GlobalMethod.InsertActivity();   
        }
Developer technologies | Windows Forms
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,656 Reputation points
    2021-01-06T05:24:27.163+00:00

    Hi VAer-4038,
    You need to change your InsertActivity method to a static method and then you can call it by using the class name.
    More details you can refer to this document.

    public static void InsertActivity()  
    {  
      //....  
    }  
    

    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.