I am updating a GridView (JobCardStatusGridView) from code behind and although I get hold of the row index, I can’t get hold of the data. here is my code.
protected void JobCardStatusGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int jobCardId = int.Parse((JobCardStatusGridView.Rows[e.RowIndex].FindControl("JobCardID") as TextBox).Text);
string completedDate = (JobCardStatusGridView.Rows[e.RowIndex].FindControl("CompletedData") as TextBox).Text;
CrewController crewManager = new CrewController();
crewManager.UpdateJobCard(jobCardId, completedDate);
JobCardStatusGridView.EditIndex = -1;
PopulateRouteStatus();
}
Here is my Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateRouteStatus();
}
}
the error I receive from the variable jobCardId is Input string was not in a correct format. When I comment that line, the error I receive from the variable completedDate is Object reference not set to an instance of an object that led me to conclude that my code does not get hold of the data. And the strangest thing is that I get hold if the row index.
Can someone help me see what I am doing wrong?
I now notice something that puzzled me more. If I populate the GridView each time the Page load, I retrieve the jobCardId variable. But when I prevent the GridView to be populated when there is a postback, for me to be able to retrieve the data, I get the errors mentioned above. I don’t really understand.
Did someone figure out what is wrong?
Thanks
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
For jobCardId the error means that the string you’re trying to parse an integer from doesn’t actually contain a valid integer.
For completedDate you have written .FindControl("CompletedData") instead of .FindControl("CompletedDate") – it should be ‘e’ instead of ‘a’.
You can try more elegant way of finding the ID and Textbox value from Gridview from below code.
Try this:
protected void JobCardStatusGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)JobCardStatusGridView.Rows[e.RowIndex];
int jobCardId = Int32.Parse(JobCardStatusGridView.DataKeys[e.RowIndex].Value.ToString());
TextBox completedDate = (TextBox)row.FindControl("CompletedData");
CrewController crewManager = new CrewController();
crewManager.UpdateJobCard(jobCardId, completedDate);
JobCardStatusGridView.EditIndex = -1;
PopulateRouteStatus();
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0