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
What is data adapter in ado.net with example?
How to retrieve the user id which is provided while windows authentication?
What are the parameters that control most of connection pooling behaviours?
What is ado circle?
How to perform sorting on a table in ADO.NET?
Why do we serialize data?
What are the key events of sqlconnection class?
How can we load multiple tables in a dataset?
What is the difference between data grid and data repeater?
What is variable view?
What are two types of transaction supported by ado.net?
What is dataset object? Explain the various objects in dataset.
What does executequery return?
Explain all the classes those are used for database connections between sql server and asp.net?
What is Serialization in .NET? what are the types of Serialization?