Reputation: 858
I have an asp.net form with a textbox and a button. Each time the button is clicked I need the text from the textbox to be added as a new row in a table, which will then be presented on a gridview.
I have managed to add the text from the textbox as a new row, but every time I click the button it seems the table is not saved (meaning - I end up with only one row).
public partial class buildTable : System.Web.UI.Page
{
DataTable dt = new DataTable();
public int namesCounter;
protected void Page_Load(object sender, EventArgs e)
{
dt.Columns.Add("ID", typeof(Int16));
dt.Columns.Add("name", typeof(string));
namesCounter = 0;
names_GV.DataSource = dt;
}
protected void addName_Click(object sender, EventArgs e)
{
namesCounter += 1;
DataRow dtrow = dt.NewRow();
dtrow["ID"] = namesCounter;
dtrow["name"] = newName_TXT.Text;
dt.Rows.Add(dtrow);
names_GV.DataBind();
}
}
I'm guessing this has something to do with postback...
Upvotes: 2
Views: 35341
Reputation: 551
This code is working properly with me, add them in button click event :
DataTable dt_items = new DataTable();
dt_items.Columns.Add("Item");
dt_items.Columns.Add("Quantity");
if (grid_items.Rows.Count > 0)
{
foreach (GridViewRow row in grid_items.Rows)
{
dt_items.Rows.Add(row.Cells[0].Text,row.Cells[1].Text);
}
}
dt_items.Rows.Add(ddl_item.SelectedItem.Text, txt_itemAmount.Text);
grid_items.DataSource = dt_items;
grid_items.DataBind();
Upvotes: 0
Reputation: 21
You need to Add the ID and Table to Viewstate so that the State is retained because, here we are not saving the Data in the Database. So every time the Page Loads, the Data is Null unless we save it in a viewstate.
Check with the Code below:- It will run perfectly :-
DataTable dt = new DataTable();
public int namesCounter;
protected void Page_Load(object sender, EventArgs e)
{
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("name", typeof(string));
//namesCounter = 0;
if (!IsPostBack)
{
ViewState["Number"] = 0;
ViewState["table"] = dt;
}
names_GV.DataSource = dt;
names_GV.DataBind();
}
protected void addName_Click(object sender, EventArgs e)
{
dt = (DataTable)ViewState["table"];
namesCounter = Convert.ToInt32(ViewState["Number"]) + 1;
ViewState["Number"] = namesCounter;
DataRow dtrow = dt.NewRow();
dtrow[0] = namesCounter;
// dtrow["ID"] = namesCounter;
dtrow["name"] = newName_TXT.Text;
dt.Rows.Add(dtrow);
ViewState["table"] = dt;
names_GV.DataSource = dt;
names_GV.DataBind();
}
Upvotes: 2
Reputation: 624
The problem here lies in the "statelessness" of asp.net. In short, each round trip to the page (first visit, post-backs) creates a new instance of buildTable
, thus re-instantiating your dt
variable and setting it as data source to your grid.
Consider sending the user input to some sort of persistence layer that enables you to hold the data per-user and rebinding said data with each post back. The strategy which could be used here really depends on the size and context of your application.
Please refer to:
Upvotes: 3