How to update a column in DataGrid using C#

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();

Questions by pen2satya

Showing Answers 1 - 3 of 3 Answers

  • Nov 1st, 2007

 Did u not set the data key property of datagrid,pl set key in data key feild

  Was this answer useful?  Yes

After seeing ur code i understood that u haven't call the bind method.

gridview1.EditItemIndex = -1;
after this u call the bind method .

gridview1.databind();//in this place u call the grid bind method n try it once.

  Was this answer useful?  Yes


  • Jun 1st, 2009

  int varid = (int)DataGrid1.DataKeys[e.Item.ItemIndex];
        TextBox lnm = (TextBox)e.Item.Cells[2].Controls[0];
        string str = lnm.Text.ToString();
        SqlCommand cmd = new SqlCommand("update customer set lastname='" + str + "' where id=" + varid, con);
        DataGrid1.EditItemIndex = -1;

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.


Related Answered Questions


Related Open Questions