GridView Updating from code behind throwing exception
I have a GridView with a list of clients and their details bound to a Sq1DataSource. I want to update it from code behind thru the RowUpdating event, by accessing data cell by cell and sending it to an Update function in my Client BLL. This is the code:
protected void gvClients_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvClients.Rows[e.RowIndex];
//accesses Client Id
cliIdStr = ((TextBox)(row.Cells[1].Controls[0])).Text;
int cliId = int.Parse(cliIdStr);
cliBll = new ClientBLL(conStrName);
//Accesses client object from DB according to Client Id accessed from gridView
client = cliBll.GetClient(cliId);
if (client != null)
{
client.ClientName = ((TextBox)(row.Cells[2].Controls[0])).Text;
client.Phone = ((TextBox)(row.Cells[3].Controls[0])).Text;
client.EMail = ((TextBox)(row.Cells[4].Controls[0])).Text;
client.Fax = ((TextBox)(row.Cells[5].Controls[0])).Text;
client.Address = ((TextBox)(row.Cells[6].Controls[0])开发者_开发百科).Text;
client.City = ((DropDownList)(row.Cells[7].Controls[0])).SelectedValue;
client.ZipCode = ((TextBox)(row.Cells[8].Controls[0])).Text;
client.IdNum = ((TextBox)(row.Cells[9].Controls[0])).Text;
client.BusField = ((TextBox)(row.Cells[10].Controls[0])).Text;
cliBll = new ClientBLL(conStrName);
cliBll.UpdateClient(cliDtlShrt);
}
}
When I run the program and press the edit button of the GridView everything is fine but when I press the Uodate button the following exception is thrown:
[ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index]
System.Web.UI.ControlCollection.get_Item(Int32 index) +8673806
pointing to this line in the code:
cliIdStr = ((TextBox)(row.Cells[1].Controls[0])).Text;
If I understand the message correctly the problem is in the Controls[0], but why? How can I access data from the gridView cells in order to send to Updating?
Your code fails because when update occurs the row offering edit UI is no longer available - the row at e.RowIndex
is a normal grid-view row whose cells will have control as per column type. So, most of cells (e.g. cells for BoundField column) will not have any control inside it as the cell directly contains the value - hence the error at Controls[0]
.
You need to use GridViewUpdateEventArgs.NewValues property to get the new values for the row (non-key columns). Similarly values for key columns will be present in e.Keys.
EDIT: I will also suggest that you consider using ObjectDataSource
instead of SqlDataSource
to make your life simpler - see this article to get you started.
精彩评论