1

I want to delete every item in the array from the database.

string[] ids = dt.AsEnumerable()
    .Select(row => row["ProductID"].ToString())
    .ToArray();

for (int i = 0; i <= ids.Length; i++) {
    string val = ids[i];
    MySqlCommand cmd1 = new MySqlCommand();
    cmd1.CommandText = "Delete from tblindividualproduct where ProductID = @p1";
    cmd1.Parameters.AddWithValue("@p1", val);
}

When I run this the line

string val = ids[i]; 

gives me an error which says:

Index was outside the bounds of the array.

What's wrong with this?

This is my whole code UPDATED

string connString = "Server=192.168.1.100;Database=product;Uid=newuser;Pwd=password";
        MySqlConnection conn = new MySqlConnection(connString);

        string[] ids = dt.AsEnumerable()
                                .Select(row => row["ProductID"].ToString())
                                .ToArray();
        try
        {
            MySqlCommand cmd1 = new MySqlCommand();
            conn.Open();
            cmd1.CommandText = "Delete from tblindividualproduct where ProductID = @p1";
            cmd1.Parameters.AddWithValue("@p1", "");
            for (int i = 0; i < ids.Length; i++)
            {
                string val = ids[i];
                cmd1.Parameters[0].Value = val;
                cmd1.ExecuteNonQuery();
            }
            MessageBox.Show("Checkout Successful");
        }
0

4 Answers 4

2

Arrays in .NET are zero based and thus the valid indexes go from zero to length - 1.
You should change your code to

   for (int i = 0; i < ids.Length; i++)

As pointed by other answer you loop also fails to call cmd1.ExecuteNonQuery and it seems that you don't have associated a connection to the MySqlCommand (thus it will not work at all).

An interesting variation on your code could be to create a single string with all of your commands and submit the command just one time.

Beware that this is not recommended unless you are absolutely sure that your ID are just numbers and not coming from user input

StringBuilder sb = new StringBuilder();
for (int i = 0; i <= ids.Length; i++) 
   sb.AppendFormat("Delete from tblindividualproduct where ProductID = {0};", ids[i]);

MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = sb.ToString();
cmd1.Connection = connection;
cmd1.ExecuteNonQuery();
Sign up to request clarification or add additional context in comments.

Comments

1

Array indexes go from 0 up to Length - 1, so you need to stop the loop before i == ids.Length. Try replacing the <= with <. Also, don't forget to call ExecuteNonQuery to execute your command.

for (int i = 0; i < ids.Length; i++) {
    string val = ids[i];
    MySqlCommand cmd1 = new MySqlCommand(conn);
    cmd1.CommandText = "Delete from tblindividualproduct where ProductID = @p1";
    cmd1.Connection = conn;
    cmd1.Parameters.AddWithValue("@p1", val);
    cmd1.ExecuteNonQuery();
}

You can also set up the command outside of the loop and only set the parameter and execute the command inside the loop:

MySqlCommand cmd1 = new MySqlCommand(conn);
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = @p1";
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("@p1", "");
for (int i = 0; i < ids.Length; i++) {
    string val = ids[i];
    cmd1.Parameters[0].Value = val;
    cmd1.ExecuteNonQuery();
}

4 Comments

i got error on cmd1.ExecuteNonQuery(); it says Connection must be valid and open but i just put conn.Open() right before the for loop
@Austria make sure you assign a valid connection to the command, usually done through the constructor of the command.
i just updated my whole code written above. Can you spot the wrong?
@MixAustria I had to step away. You've already accepted Steve's answer, but I've updated my for completeness.
1

This will be much more efficient as there's only one call to the DB, plus there's no need anymore to iterate through yours ids collection.

string[] ids = dt.AsEnumerable()
    .Select(row => row["ProductID"].ToString())
    .ToArray();

MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID IN (" + String.Join(",", ids) + ")";

2 Comments

Wrong, the parameter @p1 is considered a string and your command will be equal to IN('1,2,3,4') and no record will be deleted
Yes, better now, however I prefer to avoid IN because I am always not sure if MySql uses indexes in this scenario.
0

Your index goes from 0 to your length -1 like this:

tring[] ids = dt.AsEnumerable()
                            .Select(row => row["ProductID"].ToString())
                            .ToArray();

    for (int i = 0; i < ids.Length; i++) {
        string val = ids[i];
        MySqlCommand cmd1 = new MySqlCommand();
        cmd1.CommandText = "Delete from tblindividualproduct where ProductID = @p1";
        cmd1.Parameters.AddWithValue("@p1", val);
    }

And Index was outside the bounds of the array. means that your accessed an element that does not exist with that index.

Comments

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.