要控制RadGrid的Insert操作,您需要确保在GridViewRowInserting事件中获取所需的控件控制。以下是一个示例代码片段演示如何获取提交的值并在数据库中插入新记录:
protected void RadGrid1_InsertCommand(object sender, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command = new SqlCommand("INSERT INTO Products (ProductName, UnitPrice) VALUES (@ProductName, @UnitPrice)", connection, transaction);
command.Parameters.Add("@ProductName", SqlDbType.VarChar).Value = (editedItem.FindControl("txtProductName") as TextBox).Text;
command.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = Convert.ToDecimal((editedItem.FindControl("txtUnitPrice") as TextBox).Text);
try
{
command.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw new Exception("Insert failed", ex);
}
finally
{
connection.Close();
}
}
在上面的代码中,我们在GridViewRowInserting事件中获取了所需的控件控制,然后将这些值插入到数据库中。如果插入操作失败,则会引发异常并回滚事务。