ViewState的使用

      只知道有个叫Session的东西,可以跨页面保存变量,在它的存在时期。现在又有个叫ViewState的东西,我是没用过,现在也该开始用了,一般是用来保存控件的值或状态。
      如果你把表单用动态的table来排版,就可以来遍历控件了。
      先看页面代码:

        <table id="Table1" runat="server" style="width: 221px">
            <tr>
                <td style="width: 60px">Name</td>
                <td><asp:TextBox ID="NameTextBox" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="width: 60px">From</td>
                <td><asp:TextBox ID="FromTextBox" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="width: 60px">To</td>
                <td><asp:TextBox ID="ToTextBox" runat="server"></asp:TextBox></td>
            </tr>
        </table>

    有了runat ="server"就是服务器控件了,然后看怎么遍历。
    先是保存到各自的 ViewState

        foreach (HtmlTableRow row in Table1.Rows)
        {
            foreach (HtmlTableCell cell in row.Cells)
            {
                Control control = cell.Controls[0];
                if (control is TextBox)
                {
                    ViewState[control.ID] = ((TextBox)control).Text;
                }
            }
        }

    然后是读取出来再重新赋值

 foreach (HtmlTableRow row in Table1.Rows)
        {
            foreach (HtmlTableCell cell in row.Cells)
            {
                Control control = cell.Controls[0];
                if (control is TextBox)
                {
                    string value = (string)ViewState[control.ID];
                    if (value != null)
                    {
                        ((TextBox)control).Text = value;
                    }
                }
            }
        }

    一个最科学的方法是建立一个对应的类,然后用类来操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值