C# 如何在Asp Net GridView中更新数据

C# 如何在Asp Net GridView中更新数据,c#,asp.net,gridview,C#,Asp.net,Gridview,无法将类型为“System.Web.UI.LiteralControl”的对象强制转换为类型为“System.Web.UI.WebControl.TextBox”。更新记录时会显示此错误 我想根据id通过datagridview更新记录 protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e) { SqlConnection conn = new SqlConnection(concti

无法将类型为“System.Web.UI.LiteralControl”的对象强制转换为类型为“System.Web.UI.WebControl.TextBox”。更新记录时会显示此错误 我想根据id通过datagridview更新记录

 protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    SqlConnection conn = new SqlConnection(conctiioon);
    int userid = Convert.ToInt32(GridView2.DataKeys[e.RowIndex].Value.ToString());
    GridViewRow row = (GridViewRow)GridView2.Rows[e.RowIndex];
    //TextBox textName = (TextBox)row.Cells[0].Controls[0];
    TextBox textName = (TextBox)row.Cells[1].Controls[0];
    TextBox textprice = (TextBox)row.Cells[2].Controls[0];//here the error display 

    GridView2.EditIndex = -1;
    conn.Open();
    //SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
    SqlCommand cmd = new SqlCommand("update items set name='" + textName.Text + "',price='" + textprice.Text + "' where id='" + userid + "'", conn);
    cmd.ExecuteNonQuery();
    conn.Close();
    gvbind();
}


请指NameSapce中的System.Web.UI.WebControl(超级案例)

我模拟了您的gridview并实现了一个简单的数据源。当该单元格中有3个控件时,假设价格文本框为索引0。该单元格的第一个控件不是文本框,因此强制转换失败

不用假设索引是什么,只需使用您已经找到的GridViewRow查找控件即可

TextBox textprice = (TextBox)(row.FindControl("TextBox1"));
会的

TextBox textprice = (TextBox)Gridview2.Rows[e.Rowindex].FindControl("TextBox1");

您正在将单元格值强制转换为textbox,它实际上是一个文本控件。在下面的行TextBox textName=(TextBox)行中。单元格[1]。控件[0];是的,handel this如何将name field控件转换为literal并像使用textbox控件一样获取文字文本。在此“textprice”处显示的错误如何将其转换为literal您确定在转换单元格[2]控件时出现错误吗?