ViewState的使用

来源:互联网 发布:中石油logo相关数据 编辑:程序博客网 时间:2024/06/06 02:27

前台部分:布局如图所示: 

<div>
   
        请输入标题:<asp:TextBox ID="TextBox1" runat="server" Width="178px"></asp:TextBox>
        <br />
        请输入内容:<asp:TextBox ID="TextBox2" runat="server" Height="131px"
            TextMode="MultiLine" Width="180px"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnsave" runat="server" Text="保存" onclick="btnsave_Click" />
        <asp:Button ID="btnselect" runat="server" Text="查询" onclick="btnselect_Click" />
   
    </div>

------------------后台部分

   protected void btnsave_Click(object sender, EventArgs e)
        {
            Gushi gushi = new Gushi();
            gushi.Title = TextBox1.Text;
            gushi.Content = TextBox2.Text;
            if (ViewState["gushi"] != null)
            {
                //将ViewStae中存储的List<Gushi>对象取出来
                List<Gushi> list = ViewState["gushi"] as List<Gushi>;
                //将新的内容添加到List<Gushi>中
                list.Add(gushi);
                ViewState["gushi"] = list;
            }
            else
            {
                List<Gushi> list = new List<Gushi>();
                list.Add(gushi);
                ViewState["gushi"] = list;
            }
            TextBox1.Text = string.Empty;
            TextBox2.Text = string.Empty;
        }

        protected void btnselect_Click(object sender, EventArgs e)
        {
            TextBox2.Text = string.Empty;
            if(ViewState["gushi"]!=null)
            {
            List<Gushi> list=ViewState["gushi"] as List<Gushi>;
            foreach (Gushi item in list)
            {
                if(item.Title==TextBox1.Text)
                {
                    TextBox2.Text = item.Content;
                }
            }
            }
        }

程序运行后,我在标框看中输入php,下面也输入内容,然后输入net,同样输入内容,然后再回来查询php,

查询结果如图所示:

原创粉丝点击