DataGrid的html定义很简单,如下










功能的要求是在 ItemTemplate中,有可能是一个绑定数据源的:
<a href="...">...</a>
链接代码,也有可能是一个
<span>...</span>
显示文本代码,而判断的根据是绑定到DataGrid中数据源的DataTable中每行的某一特定列的内容。
说白了,功能就是DataGrid在绑定数据生成行的时候,判断数据源DataTable每行DataRow中一个字段的内容,这个字段类型是bool类型,如果为true,则这个列显示的是<a href="...">...</a>链接,而如果是false,则显示<span>...</span>文本。而显示的链接内指向的地址必须执行数据绑定。就是这个DataGrid的列有的行要数据绑定,有的行不要数据绑定。
功能需求分析到这里,那么现在该思考如何实现了。
我当时了解需求后,马上反应出来,使用DataGrid自带的BoundColumn、HyperLinkColumn肯定是不行的。而且,使用TemplateColumn也有麻烦。他只能放一些固定的控件,如html控件或服务器控件等。后来我没有办法了,准备继承ITemplate接口自己开发一个模版列。后来又觉得麻烦。因为绑定的时候需要一个类似于BoundColumn功能的绑定数据源内容的东西。后来我发现了这个方法。
在查看.Net Framework SDK 文档的时候,我发现在<Asp:TemplateColumn>中的<ItemTemplate>中可以放类似于



我做了一个试验,试验结果发现上面的代码(包括前面和后面的<% %>符号)输出的实际上是一个object对象,然后DataGrid显示的时候把它转换成字符串。后来我就想,是否可以前面再加入代码,调用这个页面的后台代码中的方法。
我们都知道,在asp.net1.1中,一个名称为aaa.aspx的asp.net页在asp.net内部处理时是一个名叫ASP.aaa_aspx的类,这个类继承它的后台代码aaa.aspx.cs中的类,这个类继承System.Web.UI.Page类,从而实现需要的功能。这就是说,在asp.net 1.1中,我们在.aspx中的以<% %> 包含的代码可以调用后台cs类中的以public 和protected生命的任何方法。
这就好办了,既然从上面的数据绑定代码可以获取主键内容(是个字符串),那么我可以在后台写一个方法,这个方法有一个字符串参数,返回的也是字符串。这个返回的字符串就是显示在列中的内容。
首先说一下绑定表的内容,如下
列名 | 类型 | 用途 |
fID | System.String | 表主键 |
hasSub | System.Boolean | 判断的依据 |
contentUrl | System.String | 链接的地址 |
然后是后台代码中C#代码

































然后在.aspx中的DaaGrid内这样定义:












利用了DataGrid绑定时内部使用的数据绑定方法获取结果,然后把结果传递给GetDGColumn()方法,DataGrid列的内容实际上是使用的这个方法返回的字符串。
好了,一个随心所欲生成DataGrid列内容的方法说完了,不知道大家有没有更好的方法。
我这个方法的缺点就是生成的内容没有办法执行服务器提交,它无法被服务器段区分开,所以只能是使用静态的链接,文本等。还有就是可以调用客户端的js脚本。如果谁有更好的方法,如生成的链接按钮的单击事件可以被服务器端区分,请指教。如果大家有更好的方法,也请指教。我在这里谢谢大家了。