2004年02月05日


Popup control in Internet Explorer and Mozilla



Introduction


Customizable colors


This article describes an ASP.NET popup control. This control imitates MSN Messenger alert, but it is designed for use in a web page. Graphical appearance of this control can be completely changed by using one of predefined styles or by modifying all colors used on the control. Control supports Drag&Drop, so user can move control on the page, where he wants.


A very important feature of this control is, that it can be used on most of the current browsers. It is tested with latest version of Mozilla, Internet Explorer and Opera. The look of the control is different on browsers, that doesn’t support filters (filters are supported only in newer versions of MSIE). You can also use HTML in lot of control properties, so you can get popup with icon or anything you want.


Actions


The control has two events, LinkClicked (link in popup was clicked) and PopupClosed (user clicked on ‘X’ button in popup). There are three ways how this events can be handled. The method, that will be used is determined by ActionType property. There can be following three types of actions:


Actions - Open window



  • MessageWindow (default) – If this action is selected control will open new browser window with text specified by Text property.
  • OpenLink – In this case control allows you to do any JavaScript operation or open link to any other page (Link property). You can also change target attribute of generated <A> tag. Generated code will look like this: <a href=”[Link]” target=”[LinkTarget]“>Link..</a>, so be careful when using quotes in Link. (Target attribute is added only when LinkTarget isn’t empty string.)
  • RaiseEvents – When you select this option, popup control will raise LinkClicked or PopupClosed events on server-side.

Using this control


Adding the control to a web page is very simple. In VS.NET you can just use Add/Remove Toolbox Items and select control’s DLL file. Control will appear in toolbox and you can add it to a page.


Designer


Control has rich support for designer, so you can change every property of control at design-time. In category ‘Action’ you can define, what the control should do when user clicks on link or closes popup element. Properties in categories ‘Texts’ and ‘Design’ allow you to modify control look and displayed messages. In ‘Behavior’ you can change timing (when popup will be displayed and hidden). AutoShow property indicates wether control will be displayed after page is loaded. This is usefull when you want to show control later using Anchorcontrol. If you set DragDrop to true, user can change controls position and move it on the page. ‘Window’ category allows you to change properties of window, that will appear if you set ActionType to MessageWindow. Last properties are added to category ‘Layout’ and it makes possible to modify position, where window will be displayed (offsets from bottom-left or bottom-right window corner).


Code


Following code describes how to change a few of properties and show popup control from code:

<!– Popup.aspx –>
<%@ Register TagPrefix=”cc1″ Namespace=”EeekSoft.Web”
Assembly=”EeekSoft.Web.PopupWin” %>

<cc1:popupwin id=”popupWin” runat=”server” visible=”False”
colorstyle=”Blue” width=”230px” height=”100px” dockmode=”BottomLeft”
windowscroll=”False” windowsize=”300, 200″></cc1:popupwin>

// Popup.aspx.cs
// Change action type
popupWin.ActionType=EeekSoft.Web.PopupAction.MessageWindow;

// Set popup and window texts
popupWin.Title=“This is popup”;
popupWin.Message=“<i>Message</i> displayed in popup”;
popupWin.Text=“Text to show in new window..”;

// Change color style
popupWin.ColorStyle=EeekSoft.Web.PopupColorStyle.Green;

// Change timing
popupWin.HideAfter=5000;
popupWin.ShowAfter=500;

// Show popup (after page is loaded)
popupWin.Visible=true;


Using anchor control


Designer


Page Designer


Edit properties


Adding anchor control to page at design-time is similar as adding popup control. When you add anchor to page you can select id of existing server-side control or write id of any other element and choose it’s client-side event you want to handle. If you want only reopen popup you don’t need to do anything else. You only have to ensure that popup window control will be rendered to output page (it must be visible). If you don’t want to open popup when page is loaded set AutoShow to false and popup will open after specified event occurs.


You can also change texts on popup control using PopupWinAnchor. To do this, set property ChangeTexts of anchor control to true. If this is selected, anchor control will change title of popup to NewTitle, message to NewMessage and text in optional new browser window to NewText, when client-side event is raised.


Code


Following example shows how PopupWinAnchor control can be used to reopen once closed popup control:

<!– Anchor.aspx –>
<%@ Register TagPrefix=”cc1″ Namespace=”EeekSoft.Web”
Assembly=”EeekSoft.Web.PopupWin” %>

<cc1:popupwin id=”popupWin” runat=”server” visible=”False”
colorstyle=”Blue” width=”230px” height=”100px” dockmode=”BottomLeft”
windowscroll=”False” windowsize=”300, 200″></cc1:popupwin>

<cc1:popupwinanchor id=”popupAnchor” runat=”server”
changetexts=”False”></cc1:popupwinanchor>

<span id=”spanReopen”> Click here to reopen popup ! </span>

// Anchor.aspx.cs
// Handle onclick event ..
popupAnchor.HandledEvent=“onclick”;
// .. of spanReopen element
popupAnchor.LinkedControl=“spanReopen”;
// Show popupWin when event occurs
popupAnchor.PopupToShow=“popupWin”;

// Popup win is visible ..
popupWin.Visible=true;
// .. and will be displayed when page is loaded
popupWin.AutoShow=true;


Who can use it ?


This control can be well used to notify users about important information. For example in a web email client you may want to notify the user about new message. In application where users can communicate inside system, you can use this control to alert user, that someone wants to talk to him. Benefit of this control is, that it doesn’t need any fixed space on web page and it is remarkable, so user will notice it. Another way how to use it is to show advertising information in it instead of using big Flash animations (See online demo for CodeProject banner).


Anchor control makes it possible to use popup control faster and with less page reloading. For example you can use popup control to show quick help on form fields like in this sample Quick help is displayed when textbox receives focus. Another way how to use it for quick help is to add button behind each textbox and when user clicks on this button, popup will be displayed.

原文地址:http://www.codeproject.com/aspnet/asppopup.asp













Introduction


The ASP.NET DataGrid is very powerful and robust. However, some of the things we need it to do require lots of custom code. Denis Baurer’s HierarGrid is an example of a very sophisticated datagrid. Unfortunately my project needed the ability to expand and contract datagrid columns rather than datagrid rows so I implemented the ExDataGrid server control which is described in this article. Much of the code logic was borrowed from HierarGrid.

You can check out the HierarGrid here .


Figure 1.) Contracted Columns



 


Figure 2.) Expanded Columns


Using the server control


The ExDataGrid server control requires the use of three classes:

ExDataGrid – Main server control. This is directly derived from DataGrid and has all functionality of a regular datagrid
ExColumnExpand – Column with a plus and minus image. This control is derived from BoundColumn
ExColumn – Columns that will contract/expand. This control is derived from BoundColumn and has added properties such as DrawBorders, ForeColor, and BackColor

To associate the ExColumnExpand and ExColumn classes so that they work together, the property ExGroupName must be assigned for each expanion group.

Example:

ExDataGrid id=”DataGridReport1″ runat=”server” BorderColor=”#000066″ CellPadding=”1″ BorderWidth=”2px”
AutoGenerateColumns=”False” ShowFooter=”True”>







ExColumnExpand ExGroupName=“TitleExpand” DataField=”Title” HeaderText=”Title” SortExpression=”Title” />
ExColumn DataField=”Price” ExGroupName=“TitleExpand” HeaderText=”Price” SortExpression=”Price”
DrawBorders=”true”>



ExColumn>
ExColumn DataField=”Notes” ExGroupName=“TitleExpand” HeaderText=”Notes” SortExpression=”Notes”
DrawBorders=”true”>



ExColumn>

ExColumnExpand DataField=”Publisher” ExGroupName=“PublishExpand” HeaderText=”Publisher”
SortExpression=”Publisher” />
ExColumn DataField=”Publication” ExGroupName=“PublishExpand” HeaderText=”Publication Date”
SortExpression=”Publication” DrawBorders=”false”>

ExColumn>


ExDataGrid>

 


Conclusion


This server control was quickly written and has much room for improvement. It does implement the IPostback interface so the state of the control is saved during a sort or any other rebinding of data. Additionally, the control’s expand and contract functions run via Javascript so a postback is not necessary. Please make any suggestions and or improvements as necessary. Let me know how it goes!


 


原文地址:http://www.codeproject.com/useritems/ExDataGrid.asp


Introduction


This article is being written in response of the need of building Microsoft Word document in an ASP.NET project. This article demonstrates how to create and modify document using Microsoft Word with ASP.NET.


Background


Automation is a process that allows applications that are written in languages such as Visual Basic .NET or C# to programmatically control other applications. Automation to Word allows you to perform actions such as creating new documents, adding text to documents, mail merge, and formatting documents. With Word and other Microsoft Office applications, virtually all of the actions that you can perform manually through the user interface can also be performed programmatically by using automation. Word exposes this programmatic functionality through an object model. The object model is a collection of classes and methods that serve as counterparts to the logical components of Word. For example, there is an Application object, a Document object, and a Paragraph object, each of which contain the functionality of those components in Word.


The project


The first step in manipulating Word in .NET is that you’ll need to add a COM reference to your project by right clicking in the solution explorer on References->Add Reference. Click on the COM tab and look for the Microsoft Word 10.0 Object Library. Click Select and OK.


Add Com Reference


This will automatically place an assembly in your application directory that wraps COM access to Word.


Now you can instantiate an instance of a Word application:

Word.ApplicationClass oWordApp = new Word.ApplicationClass();

You can call the interesting methods and properties that Microsoft Word provides to you to manipulate documents in Word. The best way to learn how to navigate the object models of Word, Excel, and PowerPoint is to use the Macro Recorder in these Office applications:



  1. Choose Record New Macro from the Macro option on the Tools menu and execute the task you’re interested in.
  2. Choose Stop Recording from the Macro option on the Tools menu.
  3. Once you are done recording, choose Macros from the Macro option on the Tools menu, select the macro you recorded, then click Edit.

This takes you to the generated VBA code that accomplishes the task you recorded. Keep in mind that the recorded macro will not be the best possible code in most cases, but it provides a quick and usable example.


For example to open an existing file and append some text:

object fileName = “c:\\database\\test.doc”;
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
Word.ApplicationClass oWordApp = new Word.ApplicationClass();

Word.Document oWordDoc = oWordApp.Documents.Open(ref fileName,
ref missing,ref readOnly,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible,
ref missing,ref missing,ref missing);

oWordDoc.Activate();

oWordApp.Selection.TypeText(“This is the text”);
oWordApp.Selection.TypeParagraph();
oWordDoc.Save();

oWordApp.Application.Quit(ref missing, ref missing, ref missing);


Or to open a new document and save it:

Word.ApplicationClass oWordApp = new Word.ApplicationClass();

Word.Document oWordDoc = oWordApp.Documents.Add(ref missing,
ref missing,ref missing, ref missing);

oWordDoc.Activate();

oWordApp.Selection.TypeText(“This is the text”);
oWordApp.Selection.TypeParagraph();
oWordDoc.SaveAs(“c:\\myfile.doc”);

oWordApp.Application.Quit(ref missing, ref missing, ref missing);


In C#, the Word Document class’s Open method signature is defined as Open(ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object). What this means is that in C# the Open method takes 15 required arguments, and each argument must be preceded with the ref keyword and each argument must be of type object. Since the first argument is a file name, normally a String value in Visual Basic. NET, we must declare a variable of type object that holds the C# string value, hence the code:

object fileName = “c:\\database\\test.doc”;

Although we only need to use the first argument in the Open method, remember that C# does not allow optional arguments, so we provide the final 14 arguments as variables of type object that hold values of System.Reflection.Missing.Value


Use a template


If you are using automation to build documents that are all in a common format, you can benefit from starting the process with a new document that is based on a preformatted template. Using a template with your Word automation client has two significant advantages over building a document from nothing:



  • You can have greater control over the formatting and placement of objects throughout your documents.
  • You can build your documents with less code.

By using a template, you can fine-tune the placement of tables, paragraphs, and other objects within the document, as well as include formatting on those objects. By using automation, you can create a new document based on your template with code such as the following:

Word.ApplicationClass oWordApp = new Word.ApplicationClass();
object oTemplate = “c:\\MyTemplate.dot”;
oWordDoc = oWordApp.Documents.Add(ref oTemplate,
ref Missing,ref Missing, ref Missing);

In your template, you can define bookmarks so that your automation client can fill in variable text at a specific location in the document, as follows:

object oBookMark = “MyBookmark”;
oWordDoc.Bookmarks.Item(ref oBookMark).Range.Text = “Some Text Here”;

Another advantage to using a template is that you can create and store formatting styles that you wish to apply at run time, as follows:

object oStyleName = “MyStyle”;
oWordDoc.Bookmarks.Item(ref oBookMark).Range.set_Style(ref oStyleName);

Using the class CCWordApp


The project contains a file: CCWordApp.cs. I didn’t want to write every time all the code necessary to insert text, open a file, etc…So I decided to write a class CCWordApp that wraps the most important function. This is a brief description of the class and its functions.

public class CCWordApp
{
//it’s a reference to the COM object of Microsoft Word Application
private Word.ApplicationClass oWordApplic;
// it’s a reference to the document in use
private Word.Document oWordDoc;

// Activate the interface with the COM object of Microsoft Word
public CCWordApp();

// Open an existing file or open a new file based on a template
public void Open( string strFileName);

// Open a new document
public void Open( );

// Deactivate the interface with the COM object of Microsoft Word
public void Quit( );

// Save the document
public void Save( );

//Save the document with a new name as HTML document
public void SaveAs(string strFileName );

// Save the document in HTML format
public void SaveAsHtml(string strFileName );

// Insert Text
public void InsertText( string strText);

// Insert Line Break
public void InsertLineBreak( );

// Insert multiple Line Break
public void InsertLineBreak( int nline);

// Set the paragraph alignment
// Possible values of strType :”Centre”, “Right”, “Left”, “Justify”
public void SetAlignment(string strType );

// Set the font style
// Possible values of strType :”Bold”,”Italic,”Underlined”
public void SetFont( string strType );

// Disable all the style
public void SetFont( );

// Set the font name
public void SetFontName( string strType );

// Set the font dimension
public void SetFontSize( int nSize );

// Insert a page break
public void InsertPagebreak();

// Go to a predefined bookmark
public void GotoBookMark( string strBookMarkName);

// Go to the end of document
public void GoToTheEnd( );

// Go to the beginning of document
public void GoToTheBeginning( );


So the code to open an existing file will be:

CCWordApp test ;
test = new CCWordApp();
test.Open (“c:\\database\\test.doc”);
test.InsertText(“This is the text”);
test.InsertLineBreak;
test.Save ();
test.Quit();

Details


The demo project contains:



  • CCWordApp.cs – the class
  • CreateDocModel.aspx: an example of building a new document based on a template and the use of bookmarks
  • CreateNewDoc.aspx: an example of building a new document and inserting some text
  • ModifyDocument.aspx: an example of opening an existing document and appending some text at the end
  • template\template1.dot: an example of a template (used in CreateDocModel.aspx)

Keep in mind that the directory ,in which you save the files, must be writeable. Please check the Web.config to change the path.

2004年02月04日

有的时候我们需要邦定很复杂的DataGrid,我们知道DataGrid,DataList等控件都有Template列,我们可以通过动态的邦定模版列来实现,复杂逻辑的邦定。由于Page继承TemplateControl,所以在Page对象里面就可以使用TemplateControl类里面的方法LoadTemplate,我们可以利用这个方法加载指定路径用户控件来实现丰富的表示(顺便提一下还有一个LoadControl的方法和LoadTemplate有相同的参数类型,也就是说我们可以利用LoadControl方法动态的加载用户控件,可以实现自定义的用户界面,将页面元素分成一些小的用户控件可以根据用户的定义来加载),我们还可以实现Itemplate接口实现摸版列的动态邦定。


1、使用LoadTemplate实现:


       下面我们看一个例子,我们建立一个ASP.NET的Web应用程序,在添加一个ascx的用户控件叫webusercontrol1.ascx如下所示,该用户控件里面只有一个Label控件用来邦定一个Lastname字段:


<%@ Control Language=”C#” %>


<asp:label ID=”label1″ Runat=”server” text=’<%# Databinder.Eval(((DataGridItem)Container).DataItem,”lastname”)%>’></asp:label>


      接下来我们将要创建一个DataGrid控件DataGrid1,我们将在Page_Load事件里面添加如下的代码:


string connstr = @”Integrated Security=SSPI;User ID=sa;Initial Catalog=Northwind;Data Source=MyServer\NetSDK”;


SqlConnection cnn=new SqlConnection(connstr);


SqlDataAdapter da=new SqlDataAdapter(“select * from employees”, cnn);


DataSet ds=new DataSet();


da.Fill(ds, “employees”);


ITemplate temp= Page.LoadTemplate(“webusercontrol1.ascx”);


TemplateColumn tc=new TemplateColumn();


tc.HeaderText = “Last Name”;


tc.ItemTemplate = temp;


DataGrid1.Columns.Add(tc);


DataGrid1.DataSource = ds;


DataGrid1.DataMember = “employees”;


DataGrid1.DataBind();


先面我们分析一下上面的代码,我们使用一个SQL Server里面自带的示例数据库Northwind。我们将得到所有的员工信息,然后填充数据集,然后我们声明一个Itemplate类型的对象temp用来装载邦定的用户控件。我们在声明一个TemplateColumn来动态创建一个模版列,接下来我们给该模版列添加信息,其中包括HeaderText等等,由于我们将要邦定的事ItemTemplate所以我们将刚才装载的temp赋值给该模版列的ItemTemplate对象,最后我们就将新的摸版列添加到DataGrid里面并邦定数据。


注意到上面过程,我们的用户控件里面有一个数据邦定的Label这个很重要,只有这样我们才能实现数据邦定的功能,否则就是显示一个有着相同信息的列。


2、使用Itemplate实现:


上面我们使用LoadTemplate实现动态摸版列的邦定,接下来我们将使用Itemplate接口来实现。Itemplate接口有一个方法InstantiateIn(Control container)。这个方法必须指定摸版列的父亲控件。下面的代码将会实现Itemplate接口,我们使用下面的代码创建一个新的类:


using System;


using System.Web.UI;


using System.Web.UI.WebControls;


using System.Data;


 


namespace DynamicDataGridTemplates{


public class CTemplateColumn:ITemplate{


       private string colname;


       public CTemplateColumn(string cname){


              colname=cname;


       }


       //为了使用接口必须实现的方法


       public void InstantiateIn(Control container)       {


              LiteralControl l = new LiteralControl();


              l.DataBinding += new EventHandler(this.OnDataBinding);


              container.Controls.Add(l);


       }


       public void OnDataBinding(object sender, EventArgs e){


              LiteralControl l = (LiteralControl) sender;


              DataGridItem container = (DataGridItem) l.NamingContainer;


              l.Text = ((DataRowView)       container.DataItem)[colname].ToString();


       }


}


}


在构造函数里面我们为邦定列指定了列名。我们使用InstantiateIn创建了一个LiteralControl控件l,同时我们为这个控件添加事件邦定事件,这样我们可以在邦定DataGrid的时候可以处理邦定这个控件,同时为了实现事件邦定事件,我们还编写了事件处理函数OnDataBinding,在这里我们将用指定的列邦定数据。


接下来我们将我们的自定义的摸版列动态的添加到DataGrid里面,如下的代码是Page_Load里面的:


DataGrid datagrid1=new DataGrid();


TemplateColumn tc1=new TemplateColumn();


tc1.ItemTemplate=new CTemplateColumn(“lastname”);


tc1.HeaderText=”Last Name”;


datagrid1.Columns.Add(tc1);


Page.Controls[1].Controls.Add(datagrid1);


string connstr = @”Integrated Security=SSPI;User ID=sa;Initial


Catalog=Northwind;Data Source=MyServer\NetSDK”;


SqlConnection cnn=new SqlConnection(connstr);


SqlDataAdapter da=new SqlDataAdapter(“select * from employees”, cnn)


DataSet ds=new DataSet();


da.Fill(ds, “employees”);


datagrid1.DataSource = ds;


datagrid1.DataMember = “employees”;


datagrid1.DataBind();


首先我们New一个DataGrid出来,然后声明一个模版列tc1,在设置tc1的ItemTemplate为我们自定一个模版列(不要忘了用列名这个参数),然后指定这个模版列的其他信息,最后利用DataSet邦定数据(不要忘了将控件添加到它的父控件里面,比如:datagrid1.Columns.Add(tc1);)。


上面介绍了两种动态邦定模版列的方法,希望可以对初学者有所帮助,其实这里的方法是很简单的,我想这里最关键的问题是如何理解面向对象,希望通过这篇文章的描述初学者可以对面向对象有更好的理解,我们这里使用了接口的继承以及父类子类之间的关系,通过使用接口的继承我们可以制作一个模版列的工厂可以使用同一种模式产生不同的模版列,因为我们使用的是接口(详细信息请见《设计模式》)。


 


 


本文参考http://www.dotnetbips.com网站

很多朋友都为自己编写各自使用的控件,但是所有的控件默认在工具箱中的图片都是单一的图标—齿轮。如何为自定义的控件在工具箱中自定义个性化的图标


背景:作者在编写了一个中间带数字的进度条的控件过程中,突然发现添加在工具箱中的图有点单一,于是产生了如何改用自己定义图的方式来做工具箱的图,于是查询大量的资料,翻译此文如下.该文章和原文有点出入,我修改其中一些Bug,改用自己的实例来做下面叙述. 


下面你可以通过不同的方法来完成。在下面例子中,bitmap 或icon图片必须遵循下面的规则


1、Bitmap 或icon尺寸不许是16色 16 X 16


2、底色必须是透明的


 


技术方案1: 用一个bitmap图片(不能是一个icon图片,嵌入资源)文件


不需要使用特别的ToolboxBitmapAttribute类来实现.


例如你有一个命名空间CarryNoProgramBar,自定义控件为Bar的项目。


1按照上面图片规则来建立一个命名为Bar.bmp的图片,添加该图片到你的项目,


2把该Bar.bmp的图片设置属性 生成操作设置为à嵌入的资源


3注意该图片的命名空间必须也是CarryNoProgramBar


4如果该控件的命名空间和项目的默认命名空间不匹配,你必须把该bitmap图片移到适当的子目录让他们匹配。如果你使用该方法无效,很显然你不能使用该技术来实现你自定义图片,你可以下面ToolboxBitmap属性技术来实现


5.注明我使用直接在根目录中的方式取的工具箱中的图标。


上面简单的技术来实现你的需求,而不需要你去使用ToolboxBitmapAttribute去产生你的类型


技术解决方案2:


使用ToolboxBitmap属性


使用一个和类型同名bitmap图片而非icon嵌入资源,默认的命名空间是CarryNoProgramBar


namespace CarryNoProgramBar{


[ToolboxBitmap(typeof(Bar))]


public class Bar : UserControl {…}


}


上面例运行当中,假定了你的项目根目录下存在一个命名为Bar.bmp嵌入资源图片,注意是你的图片和控件的命名空间的一致性


2 如果你需要项目中存在子目录放你的图片,你可以修改为


namespace CarryNoProgramBar{


[ToolboxBitmap(typeof(Bar),"sub.Bar.bmp")]


    public class Bar : UserControl


    {……}


}


或者


[ToolboxBitmap(typeof(Bar),"sub.Bar.ico")]


通过子目录使用,你可以使用特殊的资源,当然也包括ico文件,必须注意我上面使用了一个sub的子目录


3


有时候你的控件和图片不在同一个命名空间里,在下面的情况你必须在统一个命名空间里使用同一个类型的嵌入资源的图片


 默认命名空间


namespace MyAssemblyNamespace{


 public class SomeType


 {…}


}


namespace DifferentNamespace


{


[ToolboxBitmap(typeof(SomeType), "Bar.ico")]


public class Bar : UserControl 


{…}


}

本作者建议请直接使用同一个命名空间来调用工具箱中的图标问题,

我的上篇文章《树形结构在开发中的应用》主要是在Windows Form下的实现,下面是Web Form下的实现。


数据库设计


首先,我们在SQL SERVER 2000里建立一个表tbTree,表的结构设计如下:




























列名

数据类型

描述

长度

主键

ID

Int

节点编号

4


ParentID

Int

父节点编号

4

 

ConText

Nvarchar

我们要显示的节点内容

50

 


SQL SERVER 2000中建表的脚本:


CREATE TABLE [dbo].[tbTree] (


       [ID] [int] IDENTITY (1, 1) NOT NULL ,


       [Context] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,


       [ParentID] [int] NULL


) ON [PRIMARY]


 

在表中添加如下记录:


SET IDENTITY_INSERT tbtree ON


insert tbtree (ID,Context,ParentID)  values ( 1,’中国‘,0)


insert tbtree (ID,Context,ParentID)  values ( 2,’北京‘,1)


insert tbtree (ID,Context,ParentID)  values ( 3,’天津‘,1)


insert tbtree (ID,Context,ParentID)  values ( 4,’河北省‘,1)


insert tbtree (ID,Context,ParentID)  values ( 5,’广东省‘,1)


insert tbtree (ID,Context,ParentID)  values ( 6,’广州‘,5)


insert tbtree (ID,Context,ParentID)  values ( 7,’四川省‘,1)


insert tbtree (ID,Context,ParentID)  values ( 8,’成都‘,7)


insert tbtree (ID,Context,ParentID)  values ( 9,’深圳‘,5)


insert tbtree (ID,Context,ParentID)  values ( 10,’石家庄‘,4)


insert tbtree (ID,Context,ParentID)  values ( 11,’辽宁省‘,1)


insert tbtree (ID,Context,ParentID)  values ( 12,’大连‘,11)


insert tbtree (ID,Context,ParentID)  values ( 13,’上海‘,1)


insert tbtree (ID,Context,ParentID)  values ( 14,’天河软件园‘,6)


insert tbtree (ID,Context,ParentID)  values ( 15,’汕头‘,5)


SET IDENTITY_INSERT tbtree off




下载Treeview控件地址

http://msdn.microsoft.com/downloads/samples/internet/ASP_DOT_NET_ServerControls/WebControls/default.asp

安装后,通过自定义工具箱”->“.net框架组件TreeView添加到工具箱里。

新建一个项目,选择Visual Basic.Net 工程Asp.net Web应用程序,在页面上拖画一个TreeView控件。

 

 

Html页:


<%@ Register TagPrefix=”iewc” Namespace=”Microsoft.Web.UI.WebControls” Assembly=”Microsoft.Web.UI.WebControls, Version=1.0.2.226, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ %>


<%@ Page Language=”vb” AutoEventWireup=”false” Codebehind=”WebForm1.aspx.vb” Inherits=”Tree.WebForm1″%>


<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>


<HTML>


     <HEAD>


         <title>WebForm1</title>


         <meta name=”GENERATOR” content=”Microsoft Visual Studio .NET 7.0″>


         <meta name=”CODE_LANGUAGE” content=”Visual Basic 7.0″>


         <meta name=”vs_defaultClientScript” content=”JavaScript”>


         <meta name=”vs_targetSchema” content=”http://schemas.microsoft.com/intellisense/ie5″>


     </HEAD>


     <body MS_POSITIONING=”GridLayout”>


         <form id=”Form1″ method=”post” runat=”server”>


              <FONT face=”宋体“>


                   <iewc:TreeView id=”TreeView1″ style=”Z-INDEX: 101; LEFT: 39px; TOP: 68px” runat=”server”></iewc:TreeView></FONT>


         </form>


     </body>


</HTML>


 

 

后台代码:


    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        Dim ds As New DataSet()


        Dim CN As New SqlConnection()


        Try


            初始化连接字符串


            CN.ConnectionString = “data source=pmserver;initial catalog=Benchmark;persist security info=False;user id=sa;Password=sa;”


            CN.Open()


            Dim adp As SqlDataAdapter = New SqlDataAdapter(“select * from tbTree”, CN)


            adp.Fill(ds)


            Me.ViewState(“ds”) = ds


        Catch ex As Exception


#If DEBUG Then


            Session(“Error”) = ex.ToString()


            Response.Redirect(“error.aspx”)        ‘?跳转程序的公共错误处理页面


#End If


        Finally


            关闭连接


            CN.Close()


        End Try


        调用递归函数,完成树形结构的生成


        AddTree(0, Nothing)


    End Sub


 


    递归添加树的节点


    Private Sub AddTree(ByVal ParentID As Integer, ByVal pNode As TreeNode)


        Dim ds As DataSet


        ds = Me.ViewState(“ds”)


        Dim dvTree As New DataView()


        dvTree = New DataView(ds.Tables(0))


        过滤ParentID,得到当前的所有子节点


        dvTree.RowFilter = “PARENTID = “ + ParentID.ToString


 


        Dim Row As DataRowView


        For Each Row In dvTree


            Dim Node As New TreeNode()


            If pNode Is Nothing Then  判断是否根节点


                添加根节点


                Node.Text = Row(“ConText”).ToString()


                TreeView1.Nodes.Add(Node)


                Node.Expanded = True


                再次递归


                AddTree(Int32.Parse(Row(“ID”).ToString()), Node)


            Else


                ‘?添加当前节点的子节点


                Node.Text = Row(“ConText”).ToString()


                pNode.Nodes.Add(Node)


                Node.Expanded = True


                再次递归


                AddTree(Int32.Parse(Row(“ID”).ToString()), Node)


            End If


        Next


    End Sub


 

C#版本:

 

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using Microsoft.Web.UI.WebControls;

using System.Data.SqlClient;

namespace TreeCS

{

       /// <summary>

       /// WebForm1 的摘要说明

       /// </summary>

       public class WebForm1 : System.Web.UI.Page

       {

              protected Microsoft.Web.UI.WebControls.TreeView TreeView1;

      

              private void Page_Load(object sender, System.EventArgs e)

              {

                     // 定义数据库连接

                     SqlConnection CN = new SqlConnection();

                     try

                     {

                            //初始化连接字符串

                            CN.ConnectionString= “data source=pmserver;initial catalog=Benchmark;persist security info=False;user id=sa;Password=sa;”;

                            CN.Open();

 

                            SqlDataAdapter adp = new SqlDataAdapter(“select * from tbTree”,CN);

                            DataSet ds=new DataSet();

                            adp.Fill(ds);

                            this.ViewState["ds"]=ds;

                     }

                     catch (Exception ex)

                     {

                            Session["Error"] = ex.ToString();

                            Response.Redirect(“error.aspx”);       //?跳转程序的公共错误处理页面

                     }

                     finally

                     {

                            CN.Close();

                     }

                     //调用递归函数,完成树形结构的生成

                     AddTree(0, (TreeNode)null);

              }

 

              //递归添加树的节点

              public void AddTree(int ParentID,TreeNode pNode)

              {

                     DataSet ds=(DataSet) this.ViewState["ds"];

                     DataView dvTree = new DataView(ds.Tables[0]);

                     //过滤ParentID,得到当前的所有子节点

                     dvTree.RowFilter =  “[PARENTID] = ” + ParentID;

 

                     foreach(DataRowView Row in dvTree)

                     {

                            TreeNode Node=new TreeNode() ;

                            if(pNode == null)

                            {    //添加根节点

                                   Node.Text = Row["ConText"].ToString();

                                   TreeView1.Nodes.Add(Node);

                                   Node.Expanded=true;

                                   AddTree(Int32.Parse(Row["ID"].ToString()), Node);    //再次递归

                            }

                            else

                            {   //?添加当前节点的子节点

                                   Node.Text = Row["ConText"].ToString();

                                   pNode.Nodes.Add(Node);

                                   Node.Expanded = true;

                                   AddTree(Int32.Parse(Row["ID"].ToString()),Node);     //再次递归

                            }

                     }                  

              }           

 

              #region Web Form Designer generated code

              override protected void OnInit(EventArgs e)

              {

                     //

                     // CODEGEN该调用是 ASP.NET Web 窗体设计器所必需的。

                     //

                     InitializeComponent();

                     base.OnInit(e);

              }

             

              /// <summary>

              ///设计器支持所需的方法 – 不要使用代码编辑器修改

              /// 此方法的内容

              /// </summary>

              private void InitializeComponent()

              {   

                     this.Load += new System.EventHandler(this.Page_Load);

 

              }

              #endregion

       }

}

 

后记:请读者自行修改程序中的连接字符串设置。

 

声明:本文版权与解释权归李洪根所有,如需转载,请保留完整的内容及此声明。

QQ: 21177563  

MSN: lihonggen@hotmail.com

专栏:http://www.csdn.net/develop/author/netauthor/lihonggen0/

  •  SQL Server

    •  ODBC



      •  Standard Security:
        “Driver={SQL Server};Server=Aron1;Database=pubs;Uid=sa;Pwd=asdasd;”


      •  Trusted connection:
        “Driver={SQL Server};Server=Aron1;Database=pubs;Trusted_Connection=yes;”


      •  Prompt for username and password:
        oConn.Properties(“Prompt”) = adPromptAlways
        oConn.Open “Driver={SQL Server};Server=Aron1;DataBase=pubs;”


    •  OLEDB, OleDbConnection (.NET)



      •  Standard Security:
        “Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;User Id=sa;Password=asdasd;”


      •  Trusted Connection:
        “Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;”
        (use serverName\instanceName as Data Source to use an specifik SQLServer instance, only SQLServer2000)

      •  Prompt for username and password:
        oConn.Provider = “sqloledb”
        oConn.Properties(“Prompt”) = adPromptAlways
        oConn.Open “Data Source=Aron1;Initial Catalog=pubs;”


      •  Connect via an IP address:
        “Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;”
        (DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the port to use (1433 is the default))

    •  SqlConnection (.NET)



      •  Standard Security:
        “Data Source=Aron1;Initial Catalog=pubs;User Id=sa;Password=asdasd;”


      •  Trusted Connection:
        “Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;”
        (use serverName\instanceName as Data Source to use an specifik SQLServer instance, only SQLServer2000)

      •  Connect via an IP address:
        “Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;”
        (DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the port to use (1433 is the default))

      •  Declare the SqlConnection:

        C#:
        using System.Data.SqlClient;
        SqlConnection oSQLConn = new SqlConnection();
        oSQLConn.ConnectionString=”my connectionstring”;
        oSQLConn.Open();

        VB.NET:
        Imports System.Data.SqlClient
        Dim oSQLConn As SqlConnection = New SqlConnection()
        oSQLConn.ConnectionString=”my connectionstring”
        oSQLConn.Open()


    •  Data Shape



      •  MS Data Shape
        “Provider=MSDataShape;Data Provider=SQLOLEDB;Data Source=Aron1;Initial Catalog=pubs;User ID=sa;Password=asdasd;”


    •  Read more



      •  How to define wich network protocol to use



        • Example:
          “Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;”





















          Name Network library
          dbnmpntw Win32 Named Pipes
          dbmssocn Win32 Winsock TCP/IP
          dbmsspxn Win32 SPX/IPX
          dbmsvinn Win32 Banyan Vines
          dbmsrpcn Win32 Multi-Protocol (Windows RPC)


          Important note!
          When connecting through the SQLOLEDB provider use the syntax Network Library=dbmssocn
          and when connecting through MSDASQL provider use the syntax Network=dbmssocn



      •  All SqlConnection connectionstring properties



        • This table shows all connectionstring properties for the ADO.NET SqlConnection object. Most of the properties are also used in ADO. All properties and descriptions is from msdn.



















































































          Name Default Description
          Application Name   The name of the application, or ‘.Net SqlClient Data Provider’ if no application name is provided.
          AttachDBFilename
          -or-
          extended properties
          -or-
          Initial File Name
            The name of the primary file, including the full path name, of an attachable database. The database name must be specified with the keyword ‘database’.
          Connect Timeout
          -or-
          Connection Timeout
          15 The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.
          Connection Lifetime 0 When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by connection lifetime. Useful in clustered configurations to force load balancing between a running server and a server just brought on-line.
          Connection Reset ‘true’ Determines whether the database connection is reset when being removed from the pool. Setting to ‘false’ avoids making an additional server round-trip when obtaining a connection, but the programmer must be aware that the connection state is not being reset.
          Current Language   The SQL Server Language record name.
          Data Source
          -or-
          Server
          -or-
          Address
          -or-
          Addr
          -or-
          Network Address
            The name or network address of the instance of SQL Server to which to connect.
          Enlist ‘true’ When true, the pooler automatically enlists the connection in the creation thread’s current transaction context.
          Initial Catalog
          -or-
          Database
            The name of the database.
          Integrated Security
          -or-
          Trusted_Connection
          ‘false’ Whether the connection is to be a secure connection or not. Recognized values are ‘true’, ‘false’, and ’sspi’, which is equivalent to ‘true’.
          Max Pool Size 100 The maximum number of connections allowed in the pool.
          Min Pool Size 0 The minimum number of connections allowed in the pool.
          Network Library
          -or-
          Net
          ‘dbmssocn’ The network library used to establish a connection to an instance of SQL Server. Supported values include dbnmpntw (Named Pipes), dbmsrpcn (Multiprotocol), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmsipcn (Shared Memory) and dbmsspxn (IPX/SPX), and dbmssocn (TCP/IP).
          The corresponding network DLL must be installed on the system to which you connect. If you do not specify a network and you use a local server (for example, “.” or “(local)”), shared memory is used.
          Packet Size 8192 Size in bytes of the network packets used to communicate with an instance of SQL Server.
          Password
          -or-
          Pwd
            The password for the SQL Server account logging on.
          Persist Security Info ‘false’ When set to ‘false’, security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values including the password.
          Pooling ‘true’ When true, the SQLConnection object is drawn from the appropriate pool, or if necessary, is created and added to the appropriate pool.
          User ID   The SQL Server login account.
          Workstation ID the local computer name The name of the workstation connecting to SQL Server.


          Note
          Use ; to separate each property.
          If a name occurs more than once, the value from the last one in the connectionstring will be used.
          If you are building your connectionstring in your app using values from user input fields, make sure the user can’t change the connectionstring by inserting an additional property with another value within the user value.


    •  Access

      •  ODBC



        •  Standard Security:
          “Driver={Microsoft Access Driver (*.mdb)};Dbq=\somepath\mydb.mdb;Uid=Admin;Pwd=asdasd;”


        •  Workgroup:
          “Driver={Microsoft Access Driver (*.mdb)};Dbq=\somepath\mydb.mdb;SystemDB=\somepath\mydb.mdw;”,”admin”, “”


      •  OLEDB, OleDbConnection (.NET)



        •  Standard security:
          “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;User Id=admin;Password=asdasd;”


        •  Workgroup (system database):
          “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;Jet OLEDB:System Database=system.mdw;”,”admin”, “”


        •  With password:
          “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;Jet OLEDB:Database Password=MyDbPassword;”,”admin”, “”


    •  Oracle

      •  ODBC



        •  New version:
          “Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=Username;Pwd=asdasd;”


        •  Old version:
          “Driver={Microsoft ODBC Driver for Oracle};ConnectString=OracleServer.world;Uid=myUsername;Pwd=myPassword;”


      •  OLEDB, OleDbConnection (.NET)



        •  Standard security:
          “Provider=msdaora;Data Source=MyOracleDB;User Id=UserName;Password=asdasd;”
          This one’s from Microsoft, the following are from Oracle

        •  Standard Security:
          “Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;User Id=Username;Password=asdasd;”


        •  Trusted Connection:
          “Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;OSAuthent=1;”


      •  OracleConnection (.NET)



        •  Standard:
          “Data Source=Oracle8i;Integrated Security=yes”;
          This one works only with Oracle 8i release 3 or later

        •  Declare the OracleConnection:

          C#:
          using System.Data.OracleClient;
          OracleConnection oOracleConn = new OracleConnection();
          oOracleConn.ConnectionString = “my connectionstring”;
          oOracleConn.Open();

          VB.NET:
          Imports System.Data.OracleClient
          Dim oOracleConn As OracleConnection = New OracleConnection()
          oOracleConn.ConnectionString = “my connectionstring”
          oOracleConn.Open()


      •  Data Shape



        •  MS Data Shape:
          “Provider=MSDataShape.1;Persist Security Info=False;Data Provider=MSDAORA;Data Source=orac;user id=username;password=mypw”


    •  MySQL

      •  ODBC



        •  Local database:
          “Driver={mySQL};Server=mySrvName;Option=16834;Database=mydatabase;”


        •  Remote database:
          “Driver={mySQL};Server=data.domain.com;Port=3306;Option=131072;Stmt=;Database=my-database;Uid=username;Pwd=password;”


      •  OLEDB, OleDbConnection (.NET)



        •  Standard:
          “Provider=MySQLProv;Data Source=mydb;User Id=UserName;Password=asdasd;”

      •  MySqlConnection (.NET)



        •  EID:
          “Data Source=server;Database=mydb;User ID=username;Password=pwd;Command Logging=false”
          This one is used with eInfoDesigns dbProvider, an add-on to .NET

        •  Declare the MySqlConnection:

          C#:
          using EID.MySqlClient;
          MySqlConnection oMySqlConn = new MySqlConnection();
          oMySqlConn.ConnectionString = “my connectionstring”;
          oMySqlConn.Open();

          VB.NET:
          Imports EID.MySqlClient
          Dim oMySqlConn As MySqlConnection = New MySqlConnection()
          oMySqlConn.ConnectionString = “my connectionstring”
          oMySqlConn.Open()


    •  IBM DB2

      •  OLEDB, OleDbConnection (.NET) from ms



        •  TCP/IP:
          “Provider=DB2OLEDB;Network Transport Library=TCPIP;Network Address=XXX.XXX.XXX.XXX;Initial Catalog=MyCtlg;Package Collection=MyPkgCol;Default Schema=Schema;User ID=MyUser;Password=MyPW”


        •  APPC:
          “Provider=DB2OLEDB;APPC Local LU Alias=MyAlias;APPC Remote LU Alias=MyRemote;Initial Catalog=MyCtlg;Package Collection=MyPkgCol;Default Schema=Schema;User ID=MyUser;Password=MyPW”


    •  Sybase

      •  ODBC



        •  Standard:
          “Driver={SYBASE SYSTEM 11};Srvr=Aron1;Uid=username;Pwd=password;”


        •  Intersolv 3.10:
          “Driver={INTERSOLV 3.10 32-BIT Sybase};Srvr=Aron1;Uid=username;Pwd=password;”


    •  Informix

      •  ODBC



        •  Informix 3.30:
          “Dsn=”;Driver={INFORMIX 3.30 32 BIT};Host=hostname;Server=myserver;Service=service-name;Protocol=olsoctcp;Database=mydb;UID=username;PWD=myPwd


        •  Informix-CLI 2.5:
          “Driver={Informix-CLI 2.5 (32 Bit)};Server=myserver;Database=mydb;Uid=username;Pwd=myPwd”


    •  DSN

      •  ODBC



        •  DSN:
          “DSN=myDsn;Uid=username;Pwd=;”


        •  File DSN:
          “FILEDSN=c:\myData.dsn;Uid=username;Pwd=;”


    •  Excel

      •  ODBC



        •  Standard:
          “Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=C:\MyExcel.xls;DefaultDir=c:\mypath;”


      •  OLE DB



        •  Standard:
          “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties=Excel 8.0;HDR=Yes;”
          “HDR=Yes;” indicates that the first row contains columnnames, not data

    •  DBF / FoxPro

      •  ODBC



        •  standard:
          “Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=c:\mydbpath;”


      •  OLEDB, OleDbConnection (.NET)



        •  standard:
          “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\folder;Extended Properties=dBASE IV;User ID=Admin;Password=”


    •  Pervasive

      •  ODBC



        •  Standard:
          “Driver={Pervasive ODBC Client Interface};ServerName=srvname;dbq=@dbname”


    •  UDL

      •  UDL



        •  UDL:
          “File Name=c:\myDataLink.udl;”
    • 2004年01月31日

      asp.net中当服务器出错时显示指定的错误页面同时把错误信息写入系统日志文件的探讨


      一,在Web.config中填写出错时显示的页面,可以根据不同的statusCode显示不同的出错页面。
      <customErrors mode=”On” //如果设置为Off则出错只返回错误信息,不会跳到自己的指定页面defaultRedirect=”/error/customerrorpage.aspx”>
      <error statusCode=”404″ redirect=”/error/404Page.aspx”/>
      <error statusCode=”403″ redirect=”/error/403page.aspx”/>
      </customErrors>


      二,在Global.asax文件中添加应用出错代码,写入系统日志文件
      protected void Application_Error(Object sender, EventArgs e)
      {
      Exception LastError = Server.GetLastError();
      String ErrMessage = LastError.ToString();


      String LogName = “MyLog”;
      String Message = “Url ” + Request.Path + ” Error: ” + ErrMessage;


      // Create Event Log if It Doesn’t Exist

      if (!EventLog.SourceExists(LogName))
      {
      EventLog.CreateEventSource(LogName, LogName);
      }
      EventLog Log = new EventLog();
      Log.Source = LogName;
      //These are the five options that will display a different icon.
      Log.WriteEntry(Message, EventLogEntryType.Information, 1);
      Log.WriteEntry(Message, EventLogEntryType.Error, 2);
      Log.WriteEntry(Message, EventLogEntryType.Warning, 3);
      Log.WriteEntry(Message, EventLogEntryType.SuccessAudit, 4);
      Log.WriteEntry(Message, EventLogEntryType.FailureAudit, 5);


      }
      三,现在你可以进行测试了。
      我在Default.aspx.cs中产生一个错误,果然跳到默认的错误页面!
      private void Page_Load(object sender, System.EventArgs e)
      {
      // Put user code to initialize the page here
      try
      {
      int y=0;
      int x=1/y;
      }
      catch (Exception Err)
      {
      throw new Exception(“404″);//我想产生不同的错误,对应web.config中的statusCode,该如何实现?
      //Err.
      }