3
Answers

ASP.net Gridview operation using Entity Framework

I am performing Crud operation in asp.net using Entity framework
 
Everything thing is working fine but when i am updating the rows, it showing me null reference exception .
 
protected void datagrid1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = datagrid1.Rows[e.RowIndex];
int customerId = (int)(datagrid1.DataKeys[e.RowIndex].Value);
string firstname = (row.FindControl("txtFirstName") as TextBox).Text; //here i am getting exception, nullreference exception
string lastname = (row.FindControl("txtLastName") as TextBox).Text;
int age = Convert.ToInt32(row.FindControl("txtAge") as TextBox);
using (NORTHWNDEntities entities = new NORTHWNDEntities())
{
studentDetail customer = (from c in entities.studentDetails
where c.Id == customerId
select c).FirstOrDefault();

customer.FirstName =firstname;
customer.LastName= lastname;
customer.Age = age;
entities.SaveChanges();
}
datagrid1.EditIndex = -1;
GetStudent();
 
Any help or suggestion would be much appreciated
 
 

Answers (3)

1
Photo of Ravi Patel
NA 7.8k 532.7k 8y
Hi ,
check the update method of this url
http://www.c-sharpcorner.com/UploadFile/0c1bb2/insert-update-delete-in-gridview-using-single-stored-proce/
tryto get the firstname by this way (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString();
Accepted
1
Photo of Ashwanikumar singh
NA 37 3.4k 8y
(TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString();
This worked for me thanks
0
Photo of Vinay Singh
NA 5.9k 126.2k 8y
Hi Please check the code
TextBox txtfName= (TextBox)e.Row.FindControl("txtFirstName");
stringfirstname =txtfName.Text;
and check the link also
http://stackoverflow.com/questions/6873973/how-to-find-control-in-templatefield-of-gridview