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 / pk

public void DataGrid1_Update(Object sender,
DataGridCommandEventArgs e)
{

string unitprice =
((TextBox)e.Item.Cells[3].Controls[0]).Text;

string quantity =
((TextBox)e.Item.Cells[4].Controls[0]).Text;

string discount =
((TextBox)e.Item.Cells[5].Controls[0]).Text;

int orderid =
(int)DataGrid1.DataKeys[(int)e.Item.ItemIndex];

string productid =
((TextBox)e.Item.Cells[2].Controls[0]).Text;

try
{

string updateCmd = "UPDATE [Order Details] SET
UnitPrice = @UnitPrice,"

+ "Quantity = @Quantity, Discount = @Discount
where OrderId =@OrderId and ProductId=@ProductId";

SqlConnection cn = new SqlConnection(strConn);

SqlCommand myCommand = new SqlCommand(updateCmd,
cn);

myCommand.Parameters.Add(new
SqlParameter("@UnitPrice", Convert.ToDecimal(unitprice)));

myCommand.Parameters.Add(new
SqlParameter("@Quantity", Convert.ToInt16(quantity)));

myCommand.Parameters.Add(new
SqlParameter("@Discount", Convert.ToInt16(discount)));

myCommand.Parameters.Add(new
SqlParameter("@OrderId", orderid));

myCommand.Parameters.Add(new
SqlParameter("@ProductId", Convert.ToInt16(productid)));

cn.Open();

myCommand.ExecuteNonQuery();

DataGrid1.EditItemIndex = -1;

BindGrid();

}

catch (Exception ex)
{

lblError.Visible = true;

lblError.Text = (ex.Message);

}

Is This Answer Correct ?    2 Yes 5 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

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

521


What is dataset and datatable in ado.net?

496


Is datareader faster than datatable?

527


What is ado.net explain with diagram?

505


What is the full form of ado?

507






how we can fire event in databound coulm in datagfrid withot using button?

565


What is data control techniques?

501


What is sqldatareader?

483


Explain how to call the sql commands asynchronously in ado.net version 2.0?

498


Name which operations can you not perform on an ado.net dataset?

480


Define partial class?

503


What are the key events of sqlconnection class?

602


What are dataproviders?

543


What is ado in agriculture?

509


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

493