今天No.5说他的用Template实现的GridView在数据绑定事件中改变显示的内容后,再刷新页面时,改变的值就没了。
前台画面的片断:
- <ItemTemplate>
- <asp:Label ID="Label1" runat="server" Text='<%# Bind("PAYMENT_CD") %>'></asp:Label>
- </ItemTemplate>
数据绑定事件:
- protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- if (e.Row.RowType == DataControlRowType.DataRow)
- {
- e.Row.Cells[0].Text = "哈哈哈";
- }
- }
生成的html代码为:
- <td>哈哈哈</td>
稍微修改了一下之后,再刷新就不会丢值了,如下:
- protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- if (e.Row.RowType == DataControlRowType.DataRow)
- {
- Label lb1 = e.Row.FindControl("Label1") as Label;
- lb1.Text = "哈哈哈";
- }
- }
生成的html代码为:
- <td><span id="GridView1_ctl02_Label1">哈哈哈</span></td>
如果把前台代码修改一下就会和以前一样变得不好用了:
- <ItemTemplate>
- <asp:Label ID="Label1" runat="server" Text='<%# Bind("PAYMENT_CD") %' EnableViewState="False"></asp:Label>
- </ItemTemplate>
总结:
可见,Label中的值之所以在页面刷新时还能保持,是因为ViewState的功能,如果单纯设置e.Row.Cells[0].Text的值,仅仅只是设置在<TD>中,而只有设置在Label上,才能保持在ViewState中,当然要让Label的EnableViewState属性为True才可以。