2012-03-14 115 views
0

這裏的時候,收到錯誤的錯誤:調用公共類

An object reference is required for a non-static field, method, or property 'ArchiCapture.Models.dbConnection.runSproc(string[], string[], string)'

它出現在呼叫DT = dbConnection.runSproc(PARAMNAME,paramValue, 「pr_select_employee_by_id」);

我正在嘗試開發一個名爲SPROCs的類。這是我的班。

namespace ArchiCapture.Models 
{ 
    public class dbConnection 
    { 

    public DataTable runSproc(string[] paramName, string[] paramValue, string sproc) 
    { 
      SqlConnection conn = null; 
      DataTable dt = new DataTable(); 
      SqlDataReader reader = null; 

      try 
      { 
       string connStr = ConfigurationManager.ConnectionStrings["AC2012"].ConnectionString; 
       using (conn = new SqlConnection(connStr)) 
       { 

        SqlCommand cmd = new SqlCommand(sproc, conn); 
        cmd.CommandType = CommandType.StoredProcedure; 

        for (int x = 0; x < paramName.Count(); x++) 
        { 
         cmd.Parameters.Add(new SqlParameter(paramName[x], paramValue[x])); 
        } 
        conn.Open(); 

        reader = cmd.ExecuteReader(); 
        dt.Load(reader); 

        return dt; 
       } 
      } 
      catch (SqlException e) 
      { 
       throw (e); 
      } 
      catch (Exception ex) 
      { 
       throw (ex); 
      } 
     finally 
     { 
      if (conn != null) 
      { 
       conn.Close(); 
      } 
      if (reader != null) 
      { 
       reader.Close(); 
      } 
     } 
    } 
} 
} 

而這裏的如何,我叫它..

    DataTable dt = new DataTable(); 
       string[] paramName = new string[1] { "@employee_id" }; 
       string[] paramValue = new string[1] { searchEngine.Value }; 


       dt = dbConnection.runSproc(paramName, paramValue, "pr_select_employee_by_id"); 
+0

[非靜態字段,方法或屬性需要對象引用](http://stackoverflow.com/questions/7016437/an-object-reference-is-required-for-the -non-static-field-method-or-property) – 2012-03-14 01:06:09

+0

請不要命名以公開樣本小寫字母開頭的類。遵循[C#編碼準則](http://msdn.microsoft.com/zh-cn/library/ff926074.aspx)可使代碼更易於閱讀。 – 2012-03-14 01:08:00

回答

4

你想要一個static方法:

public static DataTable runSproc(string[] paramName, string[] paramValue, string sproc) 

或者,作爲錯誤消息狀態,必須實例化一個新的在調用實例方法之前,您的類的實例:

dbConnection conn = new dbConnection(); 
dt = conn.runSproc(paramName, paramValue, "pr_select_employee_by_id"); 

此外,通常類名是PascalCased。考慮DbConnection而不是dbConnection

+0

我是這麼一個noob,謝謝先生 – dright 2012-03-14 01:06:16

+0

@ user1196221:沒問題! – 2012-03-14 01:07:08

相關問題