0

While creating a windows form app, I was trying to call a static method in a class named 'Sqlclass' with the below code new SqlScript().Diagnose(txtServer.Text, txtDatabase.Text, txtDeptAdminAlias.Text, "GV_Diagnose.sql"); Method in the class would look like this:

public static SqlDataReader Diagnose(string server,string databasen,string alias,string sqlFile)
        {
            
            string str = Application.StartupPath + "\\Resources\\" + sqlFile;
            SqlDataReader reader=null;
            if (File.Exists(str))
            {
                FileInfo fileInfo = new FileInfo(str);
                UtilityClass gUtilityClass = new GUtilityClass("GV");
                string cmdText = fileInfo.OpenText().ReadToEnd().Replace("#USERNAME#", alias);
                SqlConnection connection = gUtilityClass.IsServerConnected();
                if (connection != null)
                {
                    SqlCommand sqlCommand = new SqlCommand(cmdText, connection);
                    try
                    {
                        sqlCommand.CommandText = cmdText;
                       sqlCommand.ExecuteReader();
                        
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            else
            {
                MessageBox.Show("File " + str + " is missing.");
            }
            return reader;
        }

Now am getting the error "Member 'SqlScript.Diagnose(string, string, string, string)' cannot be accessed with an instance reference; qualify it with a type name instead" Please excuse if I have made anything wrong

  • 1
    Simply replace `new SqlScript().Diagnose(...)` by `SqlScript.Diagnose(...)`. You can use a static method from a variable/instance. – Kalten Oct 12 '20 at 19:50
  • Remove the `new`... you can't create an instance of that class and hence, `cannot be accessed with an instance reference` error you're seeing. – Trevor Oct 12 '20 at 19:50
  • It is _SqlScript().Diagnose(....)_ Static methods are called directly on the class itself not from an instance of that class (new SqlScript). The error message is just saying that – Steve Oct 12 '20 at 19:50
  • Thank you Guys.. That Worked!! – AbhisCodeStore Oct 12 '20 at 19:59

0 Answers0