My Gridview works fine, the Editbutton cause an editbox to apear which can be edited with a new value, Having pressed Update button I see gui change back to
a static text.....
Problem; ,...... but not with the updated value. i.e. if I change value 1 to 2 press Update it change back to 1.
Having set breakpoints in both eventhandlers for RowUpdating and RowUpdated both
e.NewValues and OldValues are empty !
I want to take the updated value and update a table in a Session.
Any guess what's wrong? Do I need to bind the column "Quantity" to get the
value after updating? If so where and when? The Quantity field is the only column that is updatable. It is also the only field missing in the list of
datakeynames
Strange that my RowDeleting, .... works perfect... I'm using masterpage and VS 2008.
RowUpdating's newValues and oldValues will not be updated when you use the old style programming model. I know you're doing this because you are binding thru DataSource.
This are only populated when you use the declarative model ( SqlDataSource or ObjDataSource). So what to do?
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class UpdatingDoesNotWork : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack )
{
BindGrid();
}
}
private void BindGrid()
{
BusinessRules.BusinessRules b = new BusinessRules.BusinessRules("Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True");
GridView1.DataSource = b.GetData("Select CategoryID, CategoryName, Description from Categories");
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
//GridView1.DataBind();
BindGrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
//GridView1.DataBind();
BindGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// NewValue and OldVaule are objects that only work with the new declarative model
// that is SqlDataSource or ObjDataSource controls and the DataSourceID property of the
// GridView.
// To get data you must extrated from the Grid
// Assuming no template fields this will work string catid = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string catNam = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string catDesc = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
// Template Field is another matter. you need to know what's inside the template.
// Select the correct cells index and do a find for the control as shown below.
// string catNam = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].FindControl("txtCategoryName")).Text;
BindGrid();
// Onse you pulled everything you now need to update your data anyway you like.
// prefer this waystring sql = "Update Categories set CategoryName = '" + catNam + "' where categoryid = "
+ catid;
// No magic here this is a class that encapsulate the process of writting to
// the database
BusinessRules.BusinessRules b = new BusinessRules.BusinessRules();
b.PutData(sql);
e.Cancel = true; // this is not necessary I am just a creature of habit
GridView1.EditIndex = -1;
BindGrid();
}
}
One of the problems is getting the updated data you get this from what get postback however you want to capture the data before you refresh the data. This is important and you need to refresh to get the old information back to render on the page. This
may be a bit confusing so don't be afraid to ask questions.
It seems strange that, like in my case I'm using templated fields in the gridview, you have to retrive values from the updated grid in that fashion, is this really the best way?
I had expected this was a very straightforward and common thing to do?
1 - you do not have the benifit of the new declarative model to populate newvalue and oldvalues so and you're going to need to get the recent changes
2 - The second is that because of the first you need a way to get the changes you made (which is done at the client) before you do a grid refresh or you will loose changes.
If you really want to keep really simple stick with the declarative model! I agree it gets really obscure at times.
Your last question. In my example I think that I showed grabbing the values before and then refresh grid. Pay particular attention to how I do it the difference is important.
Here is what I ended up with doing, not sure all is needed but hey, it works! yippey!
if (!IsPostBack)
{ GridViewBasket.DataBind(); }
publicvoid RowUpdatingBasket(object o,
GridViewUpdateEventArgs e)
{
// Get new quantity value
string newQuantity = ((TextBox)GridViewBasket.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
// Get price per item
decimal Price = (Convert.ToDecimal( (String)
dt.Rows[e.RowIndex]["Price"]) );
dt.Rows[e.RowIndex].BeginEdit();
// set new quantity into datatable
dt.Rows[e.RowIndex]["Quantity"] = newQuantity;
// calculate new TotalPrice
dt.Rows[e.RowIndex]["TotalPrice"] =
Convert.ToString( (
Convert.ToDecimal( newQuantity ) ) * Price );dt.Rows[e.RowIndex].EndEdit();
// commit and save into session
dt.AcceptChanges();
Session["data"] = dt;
GridViewBasket.EditIndex = -1;
Response.Redirect("checkout.aspx");
}
Marked as answer by zombieboy on Apr 19, 2008 10:02 PM
zombieboy
0 Points
8 Posts
gridview with e.Newvalue and e.Oldvalue gone astray
Apr 16, 2008 09:31 PM|LINK
Dear Gurus [:)]
My Gridview works fine, the Editbutton cause an editbox to apear which can be edited with a new value, Having pressed Update button I see gui change back to
a static text.....
Problem; ,...... but not with the updated value. i.e. if I change value 1 to 2 press Update it change back to 1.
Having set breakpoints in both eventhandlers for RowUpdating and RowUpdated both
e.NewValues and OldValues are empty !
I want to take the updated value and update a table in a Session.
Any guess what's wrong? Do I need to bind the column "Quantity" to get the
value after updating? If so where and when? The Quantity field is the only column that is updatable. It is also the only field missing in the list of datakeynames
Strange that my RowDeleting, .... works perfect... I'm using masterpage and VS 2008.
This is how the gridview is bound to the table:
protected
void Page_Load(object sender, EventArgs e) { dt = (DataTable)Session["data"];GridViewBasket.DataSource = dt;
GridViewBasket.DataBind();
----------------------------------public void RowUpdatingBasket(object o, GridViewUpdateEventArgs e)
{
// PROBLEM: Here e.Newvalue and e.Oldvalue are empty !!!.......checkout.aspx........................................
<asp:GridView ID="GridViewBasket" runat="server" Caption="Your basket contain the following items:" AutoGenerateDeleteButton="True" autogenerateeditbutton="True" datakeynames="IDRow,IDItem,ItemName,Price,TotalPrice" onrowupdating="RowUpdatingBasket" onrowupdated="RowUpdatedBasket" onrowdeleting="RowDeletingBasket" onrowediting="RowEditingBasket" onrowcancelingedit="RowCancelingEdit" onrowcommand="RowCommand" > <EditRowStyle BackColor="Yellow" /> <AlternatingRowStyle BorderStyle="Inset" /> </asp:GridView>//on the other hand deleting works beautifully:
public void RowDeletingBasket ( object o, GridViewDeleteEventArgs e){
// Delete the row that user clicked from Basket // and add data back to session dt = (DataTable)Session["data"];dt.Rows.RemoveAt(e.RowIndex);
dt.AcceptChanges();
//commit // save delete action in session Session["data"] = dt;Response.Redirect("checkout.aspx");}
Any hints, ponderings or guesses welcome,
Zombieboy
aamador
Contributor
5211 Points
1107 Posts
Re: gridview with e.Newvalue and e.Oldvalue gone astray
Apr 17, 2008 01:33 AM|LINK
Sombieboy,
RowUpdating's newValues and oldValues will not be updated when you use the old style programming model. I know you're doing this because you are binding thru DataSource.
This are only populated when you use the declarative model ( SqlDataSource or ObjDataSource). So what to do?
Here is an example
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UpdatingDoesNotWork.aspx.cs" Inherits="UpdatingDoesNotWork" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" onrowcancelingedit="GridView1_RowCancelingEdit" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"> <Columns> <asp:CommandField ShowEditButton="True" /> <asp:BoundField DataField="CategoryID" HeaderText="Category ID" /> <asp:BoundField DataField="CategoryName" HeaderText="Category Name" /> <asp:BoundField DataField="Description" HeaderText="Description" /> </Columns> </asp:GridView> </div> </form> </body> </html>One of the problems is getting the updated data you get this from what get postback however you want to capture the data before you refresh the data. This is important and you need to refresh to get the old information back to render on the page. This may be a bit confusing so don't be afraid to ask questions.
hope this helps,
zombieboy
0 Points
8 Posts
Re: gridview with e.Newvalue and e.Oldvalue gone astray
Apr 17, 2008 08:08 AM|LINK
Hi aamador
It seems strange that, like in my case I'm using templated fields in the gridview, you have to retrive values from the updated grid in that fashion, is this really the best way?
I had expected this was a very straightforward and common thing to do?
// string catNam = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].FindControl("txtCategoryName")).Text;
Should I do BindGrid before or after I try to retrieve the updated value inside RowUpdating?
What, if anything should be done in RowUpdated?
Thanks,
Zombieboy
aamador
Contributor
5211 Points
1107 Posts
Re: gridview with e.Newvalue and e.Oldvalue gone astray
Apr 17, 2008 10:49 AM|LINK
You are facing two problems
1 - you do not have the benifit of the new declarative model to populate newvalue and oldvalues so and you're going to need to get the recent changes
2 - The second is that because of the first you need a way to get the changes you made (which is done at the client) before you do a grid refresh or you will loose changes.
If you really want to keep really simple stick with the declarative model! I agree it gets really obscure at times.
Your last question. In my example I think that I showed grabbing the values before and then refresh grid. Pay particular attention to how I do it the difference is important.
zombieboy
0 Points
8 Posts
Re: gridview with e.Newvalue and e.Oldvalue gone astray
Apr 19, 2008 10:01 PM|LINK
Thank you aamador
Your suggestion resolved the issue! [:)]
Here is what I ended up with doing, not sure all is needed but hey, it works! yippey!
if (!IsPostBack){ GridViewBasket.DataBind(); }
public void RowUpdatingBasket(object o, GridViewUpdateEventArgs e){
// Get new quantity value string newQuantity = ((TextBox)GridViewBasket.Rows[e.RowIndex].Cells[4].Controls[0]).Text; // Get price per item decimal Price = (Convert.ToDecimal( (String) dt.Rows[e.RowIndex]["Price"]) );dt.Rows[e.RowIndex].BeginEdit();
// set new quantity into datatable dt.Rows[e.RowIndex]["Quantity"] = newQuantity; // calculate new TotalPrice dt.Rows[e.RowIndex]["TotalPrice"] = Convert.ToString( ( Convert.ToDecimal( newQuantity ) ) * Price );dt.Rows[e.RowIndex].EndEdit(); // commit and save into sessiondt.AcceptChanges();
Session["data"] = dt;GridViewBasket.EditIndex = -1;
Response.Redirect("checkout.aspx");}