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

What is microsoft ado.net?

664


What is the difference between Data adaptor and Data set?

604


Why is ADO.NET serialization slower than ADO ?

668


Is ado.net an orm?

604


How to maintain the relation between two tables in ADO.NET?

621






What are the important features of ado.net 2.0?

697


Which namespaces are used for data access?

717


What is ado and rdo?

575


Can we load multiple tables in a dataset?

635


What is difference between datareader and dataadapter?

642


What is difference between Dataview and Datatable?

619


What is ambient transaction?

589


What provider ado.net use by default? Explain the role of data provider in ado.net?

616


Explain the different row versions available in table?

631


What is connection in ado.net?

611