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

Does executenonquery return a value?

539


What are the benefits of using ado.net?

518


Explain the differences between oledb sql server, oledbdotnet provider?

552


What are the Features of a dataset

666


how Sequence to connect and retrieve data from database using dataset?

754






What is data relation?

500


Define the data provider classes that is supported by ado.net?

518


What are the rules to implement connection pooling?

508


What is the role of data provider in ado.net?

550


What is difference between executequery and executeupdate?

500


What is sqldatareader in ado.net?

504


What are all the different methods under sqlcommand?

520


How to store data in memory?

508


What Is Difference Between Ado And Ado.net?

561


What is the functionality of data provider in ado.net?

489