情景:
用一个GridView显示的数据表,表中一些行可以删除,另外的行不能删除。
解决:
1 数据源: sqldatasource在获取数据时,计算数据是否可以删除。这里我使用的是一个sql的function。下面是我的selectcommand:
SELECT [ContactID], [LastName], [FirstName], [EnglishName], [WorkPhone], [MobilePhone], [Email], [Address], [City], [Province], dbo.CanDelContact([ContactID]) as CanDel FROM [ContactInfo]
2 GridView中设置数据模板列的Enable属性:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="ButtonDelete" runat="server" CommandName="Delete" Text="Delete" Enabled='<%# System.Convert.ToInt32(Eval("CanDel")) > 0 %>' />
</ItemTemplate>
</asp:TemplateField>
<%# System.Convert.ToInt32(Eval("CanDel")) > 0 %> 是在数据绑定时自动计算的。<%#表示使用数据绑顶。你可以在<%%>中间使用C#的语句进行计算。
要注意的是:GridView的asp:CommandField是不支持数据绑定的,我试过
<asp:CommandField ShowDeleteButton=<%# System.Convert.ToInt32(Eval("CanDel")) > 0 %> ButtonType =Button />
系统便以出错,因为CommandField不支持数据绑定。
所以只好增加一个模板列来解决这个问题。只要设置CommandName="Delete" ,就可以了。