Karishma
Karishma

Reputation: 199

foreach statement with parallel iterations using controls in C#

I am making an application where I am trying to store value in database from dynamically created textbox.

The code I am using is:

CheckBox clickedBtn = sender as CheckBox;
name = clickedBtn.Name;

foreach (CheckBox c in panel1.Controls.OfType<CheckBox>())
{
    if (c.Checked)
    {
        foreach(TextBox cd in panel1.Controls.OfType<TextBox>())
        {
            string val = cd.Text;

            if (val != "" && cd.Name == name)
            {
                con3.Open();

                SqlCommand cmd3 = new SqlCommand("insert into.....", con3);

                cmd3.ExecuteNonQuery();
                con3.Close();
            }
        }
    }
}

This code is working but it is entering only last checked value in the database as many times as the number of check boxes checked and I want to send the value of all the textboxes whose respective checkbox is checked.

Basically I am trying to run the foreach loops for checkboxes and textboxes run simultaneously and not inside each other.

Upvotes: 1

Views: 135

Answers (2)

Akrem
Akrem

Reputation: 4652

I have make +1 to Damith, his answer is correct, just you can optimise your code

foreach (var name in from c in panel1.Controls.OfType<CheckBox>() where c.Checked select c.Name)
{
   foreach (TextBox cd in panel1.Controls.OfType<TextBox>().Where(cd => cd.Text != "" && cd.Name == name))
   {
       con3.Open();
       SqlCommand cmd3 = new SqlCommand("insert into.....", con3);
       cmd3.ExecuteNonQuery();
       con3.Close();
    }
} 

Upvotes: 0

Damith
Damith

Reputation: 63105

remove name = clickedBtn.Name; at the top and do it inside the if (c.Checked)

foreach (CheckBox c in panel1.Controls.OfType<CheckBox>())
{
    if (c.Checked)
    {
        var name = c.Name;
        foreach (TextBox cd in panel1.Controls.OfType<TextBox>())
        {
            string val = cd.Text;
            if (val != "" && cd.Name == name)
            {
                con3.Open();
                SqlCommand cmd3 = new SqlCommand("insert into.....", con3);
                cmd3.ExecuteNonQuery();
                con3.Close();
            }
        }
    }
} 

Upvotes: 2

Related Questions