在我的asp页面中,用户可以从TextBox和搜索按钮中搜索学生。每次他们进行搜索时,学生对象都会返回。我只是希望能够用学生对象填充gridview,但每次页面加载时,页面都不记得以前的搜索。我的意思是,我的gridview结果是空的。如何填写gridview?
List<Student> oList;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
oList = new List<Student>();
}
}
protected void AddLinkButton_Click(object sender, EventArgs e)
{
Student oStudent = new Search().WithId(StudentIdTextBox.Text);
// Student object is recevied
oList.Add(oStudent);
StudentGridView.DataSource = oList;
StudentGridView.DataBind();
}
class Student { // Just a simple student class
int id;
string name;
string sname;
}
每次调用搜索方法时,我希望能够将学生数据放到DataTable中,以便我可以将它绑定到GridView。我只是不知道如何实现这一点。
答案 0 :(得分:1)
它将列表存储在会话对象中,并从会话对象绑定网格。
public partial class _Default : System.Web.UI.Page
{
List<Student> oList = new List<Student>();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["List"] = oList;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
var list = Session["List"] as List<Student>;
list.Add(new Student() { id = 1, name = "new", sname = "added" });
Session["List"] = list;
GridView1.DataSource = list;
GridView1.DataBind();
}
}
public class Student
{ // Just a simple student class
public int id{get;set;}
public string name{get;set;}
public string sname{get;set;}
}