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 a string variable?

478


What is maximum pool size in ado.net connection string?

491


Define partial class?

503


What is a datareader object?

575


What are the features of ado.net?

495






What are the advantages of using datalist?

500


What you mean by filtering of data?

529


What is the difference between the clone() and copy() methods of the dataset class?

540


What are dataproviders?

540


What is a dynaset in access?

518


What are datareaders?

523


Explain the DataAdapter.Update() and DataSetAcceptChanges() methods.

519


What are all components of ADO.Net data provider?

597


What is sqlconnection and sqlcommand?

508


What is microsoft ole db provider for sql server?

473