user2673097
user2673097

Reputation: 179

Updating Records in Gridview Using EF

I have a webpage with a gridview attached to it. The gridview allows the user to update individual records. The gridview looks like this:

JobSiteID         JobSite1
1                 13-03
2                 13-04
3                 13-06
4                 13-09
5                 13-15

I created the following record updating event handler:

protected void changeJobSiteRecordsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = changeJobSiteRecordsGridView.Rows[e.RowIndex];
    TextBox txtJobSite = row.FindControl("txtJobSite") as TextBox;

    if (txtJobSite != null)
    {
        using (ABCEntities4 Context = new ABCEntities4())
        {
            int jobSiteID = Convert.ToInt32(changeJobSiteRecordsGridView.DataKeys[e.RowIndex].Value);
            JobSite obj = Context.JobSites.First(x => x.JobSiteID == jobSiteID);
            obj.JobSite1 = txtJobSite.Text;
            Context.SaveChanges();
            changeJobSiteRecordsGridView.EditIndex = -1;
            changeJobSiteRecordsGridView.DataSource = Context.JobSites;
            changeJobSiteRecordsGridView.DataBind(); 
        }
    }
}

Here's my problem:
When I select to update, say row #2, on the first line, the local "row" variable indicates that the RowIndex == 1. However, in the second line, I expect txtJobSite variable to be populated with "13-04" but VS assigns "null" to the variable. As a result, the code flows over the if then statement below which isn't what was intended.

Any help would be greatly appreciated.

Thanks.

Upvotes: 0

Views: 34

Answers (1)

Josh
Josh

Reputation: 10604

Check the row's cells property like this:

row.Cells[1].Controls[0]

for the text box. If the '0' index doesn't work, try the 1 index. Then your code would look something like this:

TextBox txtJobSite = (TextBox)row.Cells[1].Controls[1]

I remember running into a similar problem with FindControl. This way, you explicitly find the cell and then the control in the cell.

Upvotes: 1

Related Questions