(转载,不过忘了来源了,呵呵)
开发webpart可以使用c#或者vb.net。本篇文章只介绍c#的开发方法。vb.net的如法炮制1.直接使用c#代码开发: 建立c#开发项目,在webpart1.cs中编写相应的代码。protected override void CreateChildControls()在这里写入要显示使用的控件(进行初始化)protected override void CreateChildControls(){ button1 = new Button(); button1.Text = " this.Controls.Add(button1); button1.Click +=new EventHandler(button1_Click);}事件的定义可以写在后面由用户自行书写。webpart中显示定义的控件protected override void RenderWebPart(HtmlTextWriter output){ output.write("<b>书写现实的文字</b>");button1.RenderControl(output);}编译项目后将dll文件拷贝到bin目录中。导入dwp文件便可以使用制作的webpart了。2、通过web usercontrol建立asp.net项目,然后按照平常的习惯开发webusercontrol.ascx便可。在已建立的webpart项目中添加刚才开发的webusercontrol.ascx去掉codebehind属性更改namespace和Inherits。将ascx文件的生成操作改成“嵌入的资源”。
在webpart.cs中关键是保存刚才建立的控件。protected override void CreateChildControls(){ using (StreamReader reader = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream
("aspwebpart.mycontorl.ascx")))
{ String resourceContent = reader.ReadToEnd(); using (StreamWriter writer = new StreamWriter(this.Page.Server.MapPath("/bin/mycontorl.ascx"), false))
{ writer.Write(resourceContent);}} this._innerControl = this.Page.LoadControl("/bin/mycontorl.ascx"); this.Controls.Add(this._innerControl);}最后在显示控件 protected override void RenderWebPart(HtmlTextWriter output){ this.EnsureChildControls(); this._innerControl.RenderControl(output);}这样做事程序读出原文件并写到了("/bin/mycontorl.ascx"), 中所以必须对这个目录由读写权限。3.使用kaneboy的wrappart包装器。这种办法就是省去了第二种的将usercontrol加载道webpart项目中。在服务器上安装包装器然后将开发好的usercontrol.ascx和他的dll放到相应的目录中。从叶面中选择相应的文件即可。