Background
So I just started working in ASP.Net
a few days ago. On my webpage I am creating a contact table for a user to populate and then submit to a database. Now what I have the user doing is entering information into various text boxes and then clicking an "Add Contact" button which then adds the content to a DataTable
which is stored in a Session
object. The DataSource
of my GridView
is the DataTable
.
Current State
Updated Click Event Code
Whenever I click the "Add Contact" button a new row is added to my GridView
, but nothing shows up in the cells of the GridView
.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dt.Columns.Add("First", typeof(String));
dt.Columns.Add("Last", typeof(String));
dt.Columns.Add("Email", typeof(String));
dt.Columns.Add("Phone", typeof(String));
Session["TempTable"] = dt;
GridView1.DataSource = dt;
}
else
{
dt = (DataTable)Session["TempTable"];
GridView1.DataSource = dt;
}
}
protected void AddButton_Click(object sender, EventArgs e)
{
dt = (DataTable)Session["TempTable"]; // Fetching datatable from session
DataRow dr = dt.NewRow(); // Adding new row to datatable
dr[0] = "Jenny";
dr[1] = "LastName";
dr[2] = "Jenny@hotmail.com";
dr[3] = "867-5309";
dt.Rows.Add(dr);
Session["TempTable"] = dt; // update datatable in session
GridView1.DataSource = dt; // updated datatable is now new datasource
GridView1.DataBind(); // calling databind on gridview
}
Question
Is there a property in GridView
that I am not setting or is there something fundamentally wrong with my code? Any help toward a solution would be fantastic. Thanks in advance.
Solution
I made the suggested changes by Bart De Meyer to my AddButton_Click
event and set the AutoGenerateColumns
property of my GridView
to true
.