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

How can you identify whether or not any changes are made to the DataSet object since it was last loaded?

556


What is linq and entity framework?

517


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

528


Define the executescalar method?

520


How can we load multiple tables in a dataset?

535






How to add a check box or a dropdown list to a column in a datagrid?

535


Where is adodb dll located?

527


What Is Difference Between Ado And Ado.net?

562


How to check if a datareader is closed or opened? IsClosed()

586


How is it possible to get 2 tables of data at a time by using data reader?

499


What is the advantage of ado.net?

549


What are the Features and disadvantages of dataset

557


What is the difference between linq and ado.net?

515


What is meant by ‘transaction’ in a database and what are the ‘properties of transaction’?

533


What are the major difference between classic ADO and ADO.NET?

520