DetailsView Insert后面的代码不起作用

DetailsView Insert behind the code is not working

我正在尝试通过使用在数据库中插入一些数据 detailsView插入命令。它不工作。这是我的代码 在后面。我成功地插入了 .aspx 页面,但是有一些限制,因为我也需要使用 gridview 的行作为数据,而且我只能在 aspx.cs 页面中完成它。

protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
    string Price;
    string Item;
    string PetitionType;
    string Note;
    string UserNameGV = (GridView1.SelectedRow.Cells[3].Text);
    string InvoiceGV = (GridView1.SelectedRow.Cells[5].Text);
    string CreatedDateGV = (GridView1.SelectedRow.FindControl("lblLocalTime") as Label).Text;
    SearchTB.Text = UserNameGV + " " + InvoiceGV + " " + CreatedDateGV;
    DateTime CreatedDate = Convert.ToDateTime(CreatedDateGV);

    for (Int32 attempt = 1; ;)
    {
        using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RapidVisaConnectionString"].ConnectionString))
        {
            try
            {
                Price = ((TextBox)DetailsView1.Rows[1].FindControl("TextBox2")).Text;
                Item = ((DropDownList)DetailsView1.Rows[1].FindControl("DropDownList2")).SelectedValue;
                PetitionType = ((DropDownList)DetailsView1.Rows[1].FindControl("DropDownList3")).SelectedValue;
                Note = ((TextBox)DetailsView1.Rows[1].FindControl("TextBox2")).Text;
                con.Open();
                string Sql = "INSERT INTO InvoiceDetail (Price, Item, PetitionType, Note, Paid, Quantity, Invoice, UserName, CreatedDate) VALUES (@Price, @Item, @PetitionType, @Note, @Paid, @Quantity, @Invoice, @UserName, @CreatedDate)";
                SqlCommand cmd = new SqlCommand(Sql, con);
                cmd.Parameters.AddWithValue("@Price", Price);
                cmd.Parameters.AddWithValue("@Item", Item);
                cmd.Parameters.AddWithValue("@PetitionType", PetitionType);
                cmd.Parameters.AddWithValue("@Note", Note);
                cmd.Parameters.AddWithValue("@Paid", 1);
                cmd.Parameters.AddWithValue("@Quantity", 1);
                cmd.Parameters.AddWithValue("@Invoice", InvoiceGV);
                cmd.Parameters.AddWithValue("@UserName", UserNameGV);
                cmd.Parameters.AddWithValue("@CreatedDate", CreatedDate);
                cmd.ExecuteNonQuery();
                return;
            }
            catch (SqlException sqlException)
            {
                // Increment Trys
                attempt++;
                // Find Maximum Trys
                // Override the web.config setting of 4 for retrys for this method because we are getting time-out errors.
                Int32 maxRetryCount = Int32.Parse(ConfigurationManager.AppSettings["ConnectionRetrys"]);
                //Int32 maxRetryCount = 5;
                // Throw Error if we have reach the maximum number of retries
                if (attempt == maxRetryCount)
                {
                    ErrorLog EL = new ErrorLog();
                    EL.WriteErrorWithSubjectNoWriteToDB("", "Error InvoiceDetail Max Retry");
                    //going to stop throwing an error because we are getting too many
                    //throw;
                    break;
                }
                // Determine if we should retry or abort.
                if (!SQLUtilities.RetryLitmus(sqlException))
                {
                    ErrorLog EL = new ErrorLog();
                    EL.WriteErrorWithSubjectNoWriteToDB("Insert Failed RetryLitmus for user " + UserName + ".  Sql exception number " + sqlException.Number.ToString() + ". " + sqlException.ToString(), "Error InvoiceDetail Failed Litmus");
                    //going to stop throwing an error because we are getting too many
                    //throw;
                    break;
                }
                else
                    Thread.Sleep(SQLUtilities.ConnectionRetryWaitSeconds(4));
                //Changed from default of 5 seconds to 3 seconds
                //Thread.Sleep(SQLUtilities.ConnectionRetryWaitSeconds(attempt));
            }
        }
    }
}

Here is the error message that I got.

Inserting is not supported by data source 'DetailsViewDS' unless InsertCommand is specified. The problem is I dont want to add InsertCommand in aspx page , only in aspx.cs

我已经测试了你的代码,做了一些修改并且它有效。我用的是我的db的table,你可以根据自己的需要修改。如下所述,在 DetailsView1_ItemInserting 内修改您的 SqlDataSource 和 C# 代码。它会完美地工作。

SqlDataSource:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    SelectCommand="SELECT * FROM [Image]" InsertCommand="INSERT INTO [Image] ([Name]) VALUES (@Name)">
    <InsertParameters>
        <asp:Parameter Name="Name" Type="String" />
    </InsertParameters>
</asp:SqlDataSource>

从代码后面插入

    protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        SqlDataSource sqldsInsertPassword = new SqlDataSource();
        sqldsInsertPassword.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        sqldsInsertPassword.ProviderName = ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName;
        sqldsInsertPassword.InsertCommand = "INSERT INTO Image (Name) VALUES (@Name)";
        sqldsInsertPassword.InsertCommandType = SqlDataSourceCommandType.Text;
        sqldsInsertPassword.InsertParameters.Add("Name", e.Values[0].ToString());
        sqldsInsertPassword.Insert();
    }

希望能解决您的问题。 问候!