使用了类和字典来保存数据 查询数据

类:Gushi.cs


    [Serializable]
    public class Gushi
    {
      
        public string Title { get; set; }
        public string Content { get; set; }
    }

  protected void Button1_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);
            }
            else
            {
                List<Gushi> list = new List<Gushi>();
                list.Add(gushi);
                ViewState["gushi"] = list;
            }
            TextBox1.Text = string.Empty;
            TextBox2.Text = string.Empty;
        }

        protected void Button2_Click(object sender, EventArgs e)//查询
        {
            TextBox2.Text = string.Empty;

            if(ViewState["gushi"]!=null)
            {
                List<Gushi> list=ViewState["gushi"] as List<Gushi>;
                //遍历List<Gushi>对象,查询和用户输入的标题相同的古诗,将其内容显示出来
                foreach(Gushi item in list)
                {
                  if(item.Title==TextBox1.Text)
                  {
                      TextBox2.Text = item.Content;
                  }
               
                }
            }
        }

 

 

字典

protected void Button1_Click(object sender, EventArgs e)
        {
           
            if (ViewState["gushi"] == null)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add(txttitle.Text, txtcontent.Text);
                ViewState["gushi"] = dic;
            }
            else
            {
                Dictionary<string, string> d = ViewState["gushi"] as Dictionary<string, string>;
                d.Add(txttitle.Text,txtcontent.Text);
               
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            if (ViewState["gushi"] != null)
            {
                Dictionary<string, string> dic = ViewState["gushi"] as Dictionary<string, string>;
                foreach (KeyValuePair<string, string> item in dic)
                {
                    if (item.Key == txttitle.Text)
                    {
                        txtcontent.Text = item.Value;
                    }
                }
            }
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值