10.3.4 永久管理和静态连接
通过WebPartManager上的Connections集合可以断开永久连接(用户建立的连接或在代码中使用ConnectWebParts方法建立的连接)。例如,下面的Visual Basic 2005代码提取了页面上的第一个连接。
Dim cn As WebParts.WebPartConnection
cn = Me.WebPartManager1.Connections(0)
C#的对应代码如下所示。
WebParts.WebPartConnection cn;
cn = this.WebPartManager1.Connections[0];
获得了一个Connection对象后,就可以使用该对象上的属性获得连接中涉及到的Consumer、Provider、ConnectionPoint和其他对象。还可以查看如下状态属性。
● IsActive:如果使用程序或提供程序上的一个方法正在执行,就返回True。
● IsShared:如果连接在多个使用程序中共享,就返回True。
● IsStatic:如果连接通过ASPX文件中的标记创建,就返回True。
除了Connection的ID属性之外,其他属性都是只读的。设置连接上的ID属性,以后可以按照名称来获取连接,而不是像前面的代码那样按照位置来获取。Connections集合本身有连接的通常属性。例如,Connection的Count属性可以确定页面上存在多少个连接。
下面的Visual Basic.NET代码创建了一个连接,再使用Connection集合的Count属性获取集合中的最后一个连接,给Connection的ID属性赋值。
Dim idx As Integer
If Me.WebPartManager1.CanConnectWebParts(prov, prcp(0), cons, cncp(0))
Then
Me.WebPartManager1.ConnectWebParts(prov, prcp(0), cons, cncp(0))
idx = Me.WebParManager1.Connections.Count – 1
Me.WebPartManager1.Connections(idx).ID = "NewConnection"
End If
C#的对应代码如下所示。
int idx;
if(this.WebPartManager1.CanConnectWebParts(prov, prcp(0), cons, cncp(0)))
{
this.WebPartManager1.ConnectWebParts(prov, prcp(0), cons, cncp(0));
idx = this.WebParManager1.Connections.Count - 1;
this.WebPartManager1.Connections(idx).ID = "NewConnection";
}
可以使用WebPartManager的Disconnect方法断开页面上的连接。必须给Disconnect方法传送页面上的一个连接,以删除该连接。
提示:
按照名称获取连接(只有给连接的ID属性赋了值,才能这么做),代码将更容易理解和维护。静态连接总是有一个ID——没有指定ID特性,就不能添加Connections标记。
例如,下面的Visual Basic 2005代码获取了连接NewConnection,并断开它。
Dim cn As WebControls.WebParts.WebPartConnection
cn = Me.WebPartManager1.Connections("NewConnection")
Me.WebPartManager1.DisconnectWebParts(cn)
C#的对应代码如下所示。
WebControls.WebParts.WebPartConnection cn;
cn = this.WebPartManager1.Connections["NewConnection"];
this.WebPartManager1.DisconnectWebParts(cn);
通过代码断开永久连接,会在页面的个性化设置中保存起来。
提示:
可以使用Disconnect方法,通过Connections集合删除静态连接。用户继续请求页面时,Web Part是断开的,但没有保存在页面的个性化信息中,下次用户访问该页面时,Web Part是连接的。






