user3345212
user3345212

Reputation: 131

Looping throughTextBoxes in a Panel

I have a panel that contains 5 textboxes, I am trying to loop through the Panel and insert the value of the textbox into the database if it is not 0.

my panel name is Panel1 I honestly do not know from where to start or how to loop in a Panel that contains textfields, any suggestions are appreciated:

Here is my try which it does not compile (I am not sure how to write a loop that loops through a panel)

const string query = "INSERT INTO deductible (number) VALUES (@yes)";
using (var command = new SqlCommand(query, conn))
{
foreach (Panel1 c in this.Controls)
{
    if (c.ToString() != "0")
    {
        command.Parameters.AddWithValue("@yes", c.Text);
        command.ExecuteNonQuery();
    }
}

I also attached a screenshot of my Panel1. Thank you.enter image description here

Upvotes: 0

Views: 102

Answers (3)

pmcoltrane
pmcoltrane

Reputation: 3112

You're trying to loop through items of type Panel1 in this.Controls. What you want to do is loop through items of type TextBox in Panel1.Controls.

foreach(Control c in Panel1.Controls) {
    var textbox = Control As TextBox;
    if(textbox != null){
        // do stuff...
    }
}

You also want to look at the Text property of the TextBox, not call ToString on it.

if(textbox.Text != "0"){ //do stuff... }

And you add a @yes parameter to the same command multiple times within the loop, without clearing out the parameters list. I'm not certain if that will work, but if it causes a problem, you should just be able to call command.Parameters.Clear to clear the old parameter before adding the new one.

Upvotes: 0

j.f.
j.f.

Reputation: 3939

One way is to iterate each control within your Panel that is a TextBox.

foreach (TextBox tb in Panel1.Controls.OfType<TextBox>())
{
    if (tb.Text != "0")
    {
    }
}

Upvotes: 2

sircodesalot
sircodesalot

Reputation: 11439

The simple answer is

foreach(Control control in this.Controls) { 
    if (control is TextBox) {
        // The code here ...
    }
}

The problem though is that you then need to make sure that the order the textboxes are looped over is correct, which adds more maintenance work that is entirely unnecessary. A better approach would be to learn about data binding. Or even more simply, just name your textboxes and assign them directly. Either of those is preferable to using a loop I think.

Upvotes: 4

Related Questions