-
DataGrid Update event
I am working through a walkthrough that MS provided, and their code seems to be incorrect. I placed a DataGrid on an asp page, and the data shows up, but when I click edit, then click update, I get an error. Here is the code for the Update event:
Code:
private void DataGrid1_UpdateCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
//change the data in the dataset
for (int i = 0; i < AuthorData.authors.Columns.Count; i++)
{
TextBox t = (TextBox) (e.Item.Cells[i].Controls[0]); //***THE ERROR HAPPENS HERE
DataRow row = AuthorData.authors[e.Item.DataSetIndex];
row[AuthorData.authors.Columns[i - 1].Caption] = t.Text;
}
//Update the database
if (AuthorData.HasChanges())
{
AuthorsWebClient.localhost.AuthorsService ws = new AuthorsWebClient.localhost.AuthorsService();
ws.Credentials = System.Net.CredentialCache.DefaultCredentials;
AuthorsWebClient.localhost.authors1 diffAuthors = new AuthorsWebClient.localhost.authors1();
diffAuthors.Merge(AuthorData.GetChanges());
ws.UpdateAuthors(diffAuthors);
AuthorData.Merge(diffAuthors);
}
//Take row off of edit mode and display the new data
DataGrid1.EditItemIndex = -1;
DataGrid1.DataBind();
}
The problem is it doesn't seem to like the idea of casting the cell's control to a textbox, but that's even the way MDSN shows it being done. Is this incorrect code, or is something else wrong?
Thanks.
-
I am not sure about this, but I thought I would throw it out...
Did you include the using statement for System.Windows.Forms?
using System.Windows.Forms;
That is the namespace that the Textbox is in, and if you don't have a full path to it when casting, and you haven't imported the namespace, it will throw an error.
I just looked a little harder, and you are doing asp.net....maybe it is in the System.Web.UI.WebControls namespace.
-
Mystery solved..
Actually, I copied the code wrong. The loop should start with the second column, not the first. I should have replied with the answer...sorry.