日期:2014-05-19  浏览次数:20799 次

程序中的两个DataTable 怎么建立视图?
我的程序中有两个DataTable
比如说
classTable   有两列
classID   className

studentTable有三列
studentID   classID   studentName
现在我想显示
className   studentID   studentName
这个样子的
怎么实现?谢谢
我知道在sqlserver中建立这种样子的视图很容易,但是在程序中这个怎么实现?

------解决方案--------------------
他们不在同一个数据库中,或者不在同一服务器上

不在同一个数据库中,引用:数据库名.表名
不在同一服务器上,可以使用opendatasource,或者远程链接数据库sp_addlinkedserver
------解决方案--------------------
你将要用的表导入到另一个服务器上不就行了!
------解决方案--------------------
分别连接数据库取出两个DataTable,添加其ChildRelations集合中的外键字段,然后新建一个DataSet,把两个DataTable添加到DataSet中,再向其Relations集合添加对应的关系以连接两个表,下面的示例使用 ChildRelations 属性返回 DataTable 中的每个子级 DataRelation。然后将每个关系用作 DataRow 的 GetChildRows 方法中的参数,以返回行的数组。然后输出该行中每列的值。

private static void GetChildRowsFromDataRelation()
{
/* For each row in the table, get the child rows using the
ChildRelations. For each item in the array, print the value
of each column. */
DataTable table = CreateDataSet().Tables[ "Customers "];
DataRow[] childRows;
foreach(DataRelation relation in table.ChildRelations)
{
foreach(DataRow row in table.Rows)
{
PrintRowValues(new DataRow[] {row}, "Parent Row ");
childRows = row.GetChildRows(relation);
// Print values of rows.
PrintRowValues(childRows, "child rows ");
}
}
}

public static DataSet CreateDataSet()
{
// create a DataSet with one table, two columns
DataSet dataSet = new DataSet();

// create Customer table
DataTable table = new DataTable( "Customers ");
dataSet.Tables.Add(table);
table.Columns.Add( "customerId ", typeof(int)).AutoIncrement = true;
table.Columns.Add( "name ", typeof(string));
table.PrimaryKey = new DataColumn[] { table.Columns[ "customerId "] };

// create Orders table
table = new DataTable( "Orders ");
dataSet.Tables.Add(table);
table.Columns.Add( "orderId ", typeof(int)).AutoIncrement = true;
table.Columns.Add( "customerId ", typeof(int));
table.Columns.Add( "amount ", typeof(double));
table.PrimaryKey = new DataColumn[] { table.Columns[ "orderId "] };

// create relation
dataSet.Relations.Add(dataSet.Tables[ "Customers "].Columns[ "customerId "],
dataSet.Tables[ "Orders "].Columns[ "customerId "]);

// populate the tables
int orderId = 1;
for(int customerId=1; customerId <=10; customerId++)
{
// add customer record
dataSet.Tables[ "Customers "].Rows.Add(
new object[] { customerId,
string.Format( "customer{0} ", customerId) });

// add 5 order records for each customer
for(int i=1; i <=5; i++)
{
dataSet.Tables[ "Orders "].Rows.Add(
new object[] { orderId++, customerId, orderId * 10 });
}
}

return dataSet;
}

private static void PrintRowValues(DataRow[] rows, string label)
{
Console.WriteLine( "\n{0} ", label);
if(rows.Length <= 0)
{
Console.WriteLine( "no rows found ");
return;
}