0

I have a Panel that contains 3 textfields, in each textfield a user can enter an age. Everything seems to work correctly except the part where it stops if a user enters a number in two or more textfields (The loop is working, it just does not insert the next textfield value into the database) This is the scenario:

Depdent 1 Age: 10
Depdent 1 Age: 12
Depdent 1 Age: 14

What I want to be inserted into my table is the following

ID      age
1       10
2       12
3       14

when I hit submit, it only inserts the first record then throws an error, I know the error is causes by trying to insert two textfield values into a cell in the database however I do not know how to fix it, my table has an ID field which is a primary key and auto increment. Any advises are appreciated. Thank you.

Here is my code:

const string query = "INSERT INTO deductible (age) VALUES (@age)";
using (var command = new SqlCommand(query, conn))
{
foreach (TextBox tb in Panel1.Controls.OfType<TextBox>())
{
    if (tb.Text != "0")
    {
        command.Parameters.AddWithValue("@age", tb.Text);
        command.ExecuteNonQuery();
    }
}

1 Answer 1

2

Use SqlParameterCollection.Clear Method after executing the query:

if (tb.Text != "0")
{
    command.Parameters.AddWithValue("@age", tb.Text);
    command.ExecuteNonQuery();
    command.Parameters.Clear();
}
Sign up to request clarification or add additional context in comments.

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.