Why this problem happens is Asp.Net cannot persist the changes in DataTable you created between different requested. You need to write code to persist these changes. One solution is to store the data table in a Session variable after adding the new row. Also make sure to retrieve the same data table from this session before adding the next row.
The code will look like this;
DataTable dt1=new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["a"] = null;
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if Session["a"]==null)
{
gridVIEWData();
Int32 total = Convert.ToInt32(txt_quantity.Text) * Convert.ToInt32(txt_price.Text);
DataRow dr = dt1.NewRow();
dr["pName"] = DropDownList2.SelectedItem;
dr["pCategory"] = DropDownList1.SelectedItem;
dr["price"] = txt_price.Text;
dr["pQuantity"] = txt_quantity.Text;
dr["totalPrice"] = total;
dt1.Rows.Add(dr);
Session["datas"]=dt1;
GridView1.DataSource = dt1;
GridView1.DataBind();
}
else {
Int32 total = Convert.ToInt32(txt_quantity.Text) * Convert.ToInt32(txt_price.Text);
DataTable dtcached = (DataTable)Session["a"];
DataRow dr = dtcached.NewRow();
dr["pName"] = DropDownList2.SelectedItem;
dr["pCategory"] = DropDownList1.SelectedItem;
dr["price"] = txt_price.Text;
dr["pQuantity"] = txt_quantity.Text;
dr["totalPrice"] = total;
DataTable dtCached=(DataTable)Session["datas"];
dtCached.Rows.Add(dr);
GridView1.DataSource = dtCached; GridView1.DataBind();
}
}
Changed code I have shown it in BOLD, Hope this helps.. It is not good to use lot of session variable as it adds more loads to server, but it gives you a hint