1

I'm stuck on the means to properly and best run a stored procedure to insert records through a foreach loop.

Here is what I have so far.

    string constr = ConfigurationManager.ConnectionStrings["CurrencyDb"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr)) {
    con.Open();
        foreach (ListItem i in DependenciesListBox.Items) {
            if (i.Selected) {
                using (SqlCommand cmd = new SqlCommand("dbo.InsertDependency", con)) {
                    try {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@CurrencyId", scopeidentity);
                        cmd.Parameters.AddWithValue("@DependencyId", i.Value);
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqlex) {
                        throw new Exception("SQL Exception on insert. " + sqlex.Message);
                    }
                    catch (Exception ex) {
                        throw new Exception("Error adding dependencies. " + ex.Message);
                    }
                }
            }
        }

        foreach (ListItem i in AffectedListBox.Items) {
            if (i.Selected) {
                using (SqlCommand cmd = new SqlCommand("dbo.InsertAffected", con)) {
                    try {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@DependencyId", scopeidentity);
                        cmd.Parameters.AddWithValue("@CurrencyId", i.Value);
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqlex) {
                        throw new Exception("SQL Exception on insert. " + sqlex.Message);
                    }
                    catch (Exception ex) {
                        throw new Exception("Error adding affected apps. " + ex.Message);
                    }
                }
            }
        }

        //Loops through Platform list box and for each item that's selected, add a record into the platform table in the database.
        foreach (ListItem i in PlatformListBox.Items) {
            if (i.Selected) {
                using (SqlCommand cmd = new SqlCommand("dbo.InsertPlatform", con)) {
                    try {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@CurrencyId", scopeidentity);
                        cmd.Parameters.AddWithValue("@PlatformId", i.Value);
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqlex) {
                        throw new Exception("SQL Exception on insert. " + sqlex.Message);
                    }
                    catch (Exception ex) {
                        throw new Exception("Error adding platforms. " + ex.Message);
                    }
                }
            }
        }
    }

Doing it this way, I get the following error (Updated)

Uncaught Error: Sys.WebForms.PageRequestManagerServerErrorException: Error adding dependencies. The connection was not closed. The connection's current state is open.
    at Function.Error.create (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at Sys.WebForms.PageRequestManager._createPageRequestManagerServerError (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at Sys.WebForms.PageRequestManager._parseDelta (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at Sys.WebForms.PageRequestManager._onFormSubmitCompleted (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at Array.<anonymous> (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1
    at Sys.Net.WebRequest.completed (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at XMLHttpRequest._onReadyStateChange (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)

Would anyone be able to let me know what the best practice is for doing this kind of thing? Thank you so much in advance.

2
  • Please add your error message as text, not an image. It makes it easier to read, and search for. Commented Mar 20, 2017 at 14:32
  • You're right, my apologies. Commented Mar 20, 2017 at 14:32

1 Answer 1

1

Don't call con.Open(); multiple times. Move it to

using (SqlConnection con = new SqlConnection(constr)) {
  con.Open();
  ...

See the first row in the Exceptions table:

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx

Sign up to request clarification or add additional context in comments.

7 Comments

I knew it was going to be something silly. Let me try this out, thank you.
@David - because you have con.Open(); in three different loops - remove all of them and leave only one as shown
Yes I removed all three and left one right after using (SqlConnection con = new SqlConnection(constr)) { I'll update my code.
Ok, I'll do so via text this time.
@David - you are running old code, make sure the binaries are rebuilt
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.