How To Update A Column In A DataGrid Using C#.NET?

I am getting InvalidCastException as (Specified cast is not
valid) while updating 2nd column in a datagrid?
Id,firstname,lastname are the three columns of my datagrid
respectively. I wanted to edit the second column(lastname)
and update it. I did the following code in DataGrid's
updatecommand(),but failed to update !

Int varid=(int)DataGrid1.DataKeys[e.Item.ItemIndex];
TextBox lnm=(TextBox)e.Item.Cells[2].Controls[0]; string
str=lnm.Text ; SqlCommand cmd=new SqlCommand("update
customer set lastname='" + str + "' where id=" + varid
+ "",con); cmd.ExecuteNonQuery(); DataGrid1.EditItemIndex=-
1; DataGrid1.DataBind();

Answer Posted / aravazhi

Try this query you can avoid InvalidCastException...

string strQry = "update customer set lastname=@LastName
where id=@VarId";
SqlCommand cmd=new SqlCommand(strQry,con);
int varid = (int)DataGrid1.DataKeys[(int)e.Item.ItemIndex];
string LName = ((TextBox)e.Item.FondControl
("txtLName")).Text;//txtLname is ID of control
cmd.Paramters.Add(new SqlParameter("@LastName",LName));
cmd.Paramters.Add(new SqlParameter("@VarId",varid));
cmd.ExecuteNonQuery();
DataGrid1.EditItemIndex=- 1;
DataGrid1.DataBind();

Is This Answer Correct ?    15 Yes 4 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Define ado.net?

825


What is serialization and de-serialization in .net? How can we serialize the dataset object?

749


What is Data view?

810


How to pass values into a datatable?

862


How can I retrieve two tables of data at a time by using data reader?

750


What is row state?

740


What is acid in ado.net?

749


How to connect and retrieve data from database using dataset

784


How would you connect to a database by using .NET?

737


What is dbcontext and dbset in entity framework?

708


What is sqldatasource?

728


How to perform sorting on a table in ADO.NET?

788


What we do with the object of ado.net dataset after using it?

744


What is a dynaset in access?

835


What are the core objects of ADO.NET?

811