Question

I am trying to delete all the rows in the table with for loop but i cant do it. I am counting the rows from the table with reportBindingSource.count, but i cant find the way to delete the whole line FROM data base ( id, nameofcase, price).

  private void button1_Click(object sender, EventArgs e)
        {
            //delete all lines from the table

            count = reportBindingSource.Count;
            MessageBox.Show(count.ToString());

            for (int x = 0; x < count; x++) 
            {

                try
                {

                    //delete

                }
                catch(Exception ex)
                {
                    MessageBox.Show("not deleted");
                }

                MessageBox.Show(x.ToString());
            }
            this.Close();

        }

Anyone can help me?

UPDATE 1

 try
                {

                    using(SqlConnection cnn = new SqlConnection("server=kosh-pc;User Id=root;Persist Security Info=True;database=lawyersprice"))
                    using(SqlCommand cmd = new SqlCommand("TRUNCATE TABLE report", cnn))
                     {
                         cnn.Open();
                         cmd.ExecuteNonQuery();
                     }

                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

I try this based on the answer but is not connecting and yes i have the .net installed

Was it helpful?

Solution

To remove all elements from the a BindingSource you need to simply call the

 reportBindingSource.Clear();

and no need to loop over the single elements

If you want to remove all the rows from the database table then you need to prepare and execute a Sql Command appropriate for your database type.

Example for MySql - Needs the MySql NET Connector and the appropriate references to MySql.Data.dll

(Warning this removes the rows from the database without any exception)

 using(MySqlConnection cnn = new MySqlConnection(....connectionstring..))
 using(MySqlCommand cmd = new MySqlCommand("TRUNCATE TABLE yourTableName", cnn))
 {
     cnn.Open();
     cmd.ExecuteNonQuery();
 }

instead, if you have a condition then you need

(This removes only the rows from the database that satisfy the condition)

 using(MySqlConnection cnn = new MySqlConnection(....connectionstring..))
 using(MySqlCommand cmd = new MySqlCommand("DELETE FROM yourTableName WHERE ... your condition...", cnn))
 {
     cnn.Open();
     cmd.ExecuteNonQuery();
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top