简体   繁体   中英

DetailsView Insert behind the code is not working

I'm trying to insert some data in the database through using detailsView insert command. And Its not working. Here is my code behind. I manage to successfully insert in the .aspx page buti has some limitations, since I need to use the row of the gridview as data also and I can only accomplish it if I do it in the aspx.cs page.

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

I've tested your code, did some modifications and it works. I've used table of my db, you can modify it according to your need. Modify your SqlDataSource and C# code within DetailsView1_ItemInserting as mentioned below. It will work perfectly.

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>

Insertion from code behind

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

I hope it will solve your issue. Regards!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM