类: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;
}
}
}
}