2010-12-04 175 views
0

我在其中一個類中有這樣的函數,然後我需要在另一個類中調用它,並獲取默認數據表中的值。在默認數據表中調用函數從一個類到另一個類

public DataTable GetPrimaryKeyTables(string localServer, string userName, string password, string selectedDatabase) 
{ 
     // Create the datatable 
     DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames"); 

     SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder(); 
     objConnectionString.DataSource = localServer; ; 
     objConnectionString.UserID = userName; 
     objConnectionString.Password = password; 
     objConnectionString.InitialCatalog = selectedDatabase; 

     // Query to select primary key tables. 
     string selectPrimaryKeyTables = @"SELECT 
               TABLE_NAME 
               AS 
               TABLES 
              FROM 
               INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
              WHERE 
               CONSTRAINT_TYPE = 'PRIMARY KEY' 
             ORDER BY 
               TABLE_NAME"; 

     // put your SqlConnection and SqlCommand into using blocks! 
     using(SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString)) 
     using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection)) 
     { 
      try 
      { 
       // Create the dataadapter object 
       SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection); 

       // Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself 
       // (and also close it again after it is done) 
       sDataAdapter.Fill(dtListOfPrimaryKeyTables); 
       dgResultView.DataSource = dtListOfPrimaryKeyTables; 
      } 
      catch(Exception ex) 
      { 
       //All the exceptions are handled and written in the EventLog. 
       EventLog log = new EventLog("Application"); 
       log.Source = "MFDBAnalyser"; 
       log.WriteEntry(ex.Message); 
      } 
     } 

     // return the data table to the caller 
     return dtListOfPrimaryKeyTables; 
    } 

任何人都可以幫助我,每次嘗試時,控件都不會從一個類繼承到另一個類。

+0

這就是你問昨天一樣的問題http://stackoverflow.com/questions/4345506/defining-function-in-one-class-and-calling-in-other-class-is-not-inheriting-所述-C / – jvanrhyn 2010-12-04 07:07:56

回答

3

我不確定你的意思是「控制不從一個類繼承到另一個類」。

您將在另一個類中創建此類的對象並調用其上的方法。

像這樣

class class1 
{ 
    public DataTable GetPrimaryKeyTables(string localServer, string userName, string password, string selectedDatabase) 


    ....... 
    ........ 
    return dtListOfPrimaryKeyTables; 


} 
class Class2 
{ 
    protected void BindControl(....) 
    { 
     DataTable dt = new class1().GetPrimaryKeyTables(......); 
     dgResultView.DataSource = dt; 
     dgResultView.DataBind(); 

    } 

} 

要麼將​​「dgResultView」作爲參數傳遞給該方法或使用上面的代碼段。控件被定義爲「受保護」,因此它們不會在其他類中訪問。在函數中使用的dgResultView.DataSource = dtListOfPrimaryKeyTables;是不會工作的。

將連接字符串和其他信息放在配置文件中並從中進行訪問是個好主意。

相關問題