Cute Bear
Cute Bear

Reputation: 3293

Filling a DataTable

In my asp page users can search students from TextBox and a search button. Every time they made a search a student object returns. I just want to be able to fill a gridview with student object but every time page loads, the page doesn't remember the former searches. What I mean by this, my gridview turns out empty. How can I fill a 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;
}

Every time search method is called, I want to be able to put the student data to DataTable so that I can bind it to GridView. I just dont know how to achieve this.

Upvotes: 0

Views: 449

Answers (1)

AnarchistGeek
AnarchistGeek

Reputation: 3196

do you want to achieve something like this? I will improve my answer if you need.

it stores the list in a session object and bind the grid from session object.

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

Upvotes: 1

Related Questions