NewbieLearner
NewbieLearner

Reputation: 11

Duplicate data in database

I try to insert datagridview value and textbox simultnaeously after a button clicked but the data were duplicated in the database.

Database duplicate image

Datagridview display

Can anyone tell me what's the problem in my code, please?

My code

       private void btnPay_Click(object sender, EventArgs e)
    {

            decimal pay, balance, total;


            total = decimal.Parse(txtNetTotal.Text);

            pay = decimal.Parse(txtCash.Text);

            balance = pay - total;

            txtCash.Text = pay.ToString("0.00");
            txtBalance.Text = balance.ToString("0.00");


        try
        {

            foreach (DataGridViewRow row in dgvOrder.Rows)
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
                SqlCommand cmd = new SqlCommand("insert into tblOrder (ProductName,Quantity,ProductPrice,TotalPrice,Cash,Balance)" +
                                                "values (@ProductName,@Quantity,@ProductPrice,@TotalPrice,@Cash,@Balance)", con);
                cmd.Parameters.AddWithValue("@ProductName", Convert.ToString(row.Cells["colProduct"].Value));
                cmd.Parameters.AddWithValue("@Quantity", Convert.ToString(row.Cells["colQuantity"].Value));
                cmd.Parameters.AddWithValue("@ProductPrice", Convert.ToString(row.Cells["colPrice"].Value));
                cmd.Parameters.AddWithValue("@TotalPrice", txtTotal.Text.Trim());
                cmd.Parameters.AddWithValue("@Cash", txtCash.Text.Trim());
                cmd.Parameters.AddWithValue("@Balance", txtBalance.Text.Trim());

                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
        catch(SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Here the whole code for the button event.

Upvotes: 1

Views: 114

Answers (1)

David
David

Reputation: 218818

Based on comments above and on the image edited into the question, your DataGridView has two rows. Which is why this loop is inserting two rows into the database:

foreach (DataGridViewRow row in dgvOrder.Rows)

It looks like the second row is a blank one, which explains why the second database entry has only the static values and not the row-based values. To prevent this, you should be able to add a simple conditional:

foreach (DataGridViewRow row in dgvOrder.Rows)
{
    if (!row.IsNewRow)
    {
        // insert into the database
    }
}

Or, if nested code blocks are unsightly:

foreach (DataGridViewRow row in dgvOrder.Rows)
{
    if (row.IsNewRow)
        continue;
    // insert into the database
}

Upvotes: 2

Related Questions