在默认数据表中调用函数从一个类到另一个类
问题描述:
我在其中一个类中有这样的函数,然后我需要在另一个类中调用它,并获取默认数据表中的值。在默认数据表中调用函数从一个类到另一个类
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;
}
任何人都可以帮助我,每次尝试时,控件都不会从一个类继承到另一个类。
答
我不确定你的意思是“控制不从一个类继承到另一个类”。
您将在另一个类中创建此类的对象并调用其上的方法。
像这样
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;
是不会工作的。
将连接字符串和其他信息放在配置文件中并从中进行访问是个好主意。
这就是你问昨天一样的问题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