今天在做一个页面时用到了DataGrid控件,第一列为模板列,我在其中放了一个CheckBox控件,但在后台中使用
CheckBox cb=(this.DataGrid1.Items[i].Cells[0].Controls[0] as CheckBox);
语句却出现错误,苦思不得其解,最后从网络上得到原因:
由于我的Html源码为:
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 40px" runat="server"
Width="800px" Height="176px">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server" Text="选择"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
... ...
在<ItemTemplate>与<asp:... ...>之间有空格,.net将该空格看做了System.Web.UI.LiteralControl类型的控件,所以需要把空格去掉就可以了
修改后的代码为:
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 40px" runat="server"
Width="800px" Height="176px">
<Columns>
<asp:TemplateColumn>
<ItemTemplate><asp:CheckBox id="CheckBox1" runat="server" Text="选择"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
... ...