All,
i have a bunch of dynamic checkboxes created in a datagrid, and i have the results going to a database when they are checked. question is how do i count the total # of checkboxes checked. here is the code i have that loops through the checkboxes to submit to the db.

foreach (DataGridItem spriden_ID in dgEmployees.Items)
                {
                    CheckBox cbSpriden = (CheckBox) spriden_ID.FindControl("cbSpriden");
                    if (cbSpriden.Checked)
                    {
                       //Stuff to add to db here
                        }
                        else
                        {       
                            lblStatus.Text ="Scheduling failed: " + addCourses.ErrorMessage;
                        }
                    }

Once the update to the DB succeeds i want to display the count of all the checkboxes submitted..how would i do this?? thanks in advance for any help.

Dani AI

Generated

Short answer: collect the checked rows first, update the database in one go (or track which updates actually succeeded), then show the collection size once—do not build the display text while you are looping. and were on the right track about counting; highlighted the common string-concatenation trap. The code below shows a compact, different pattern that avoids per-item UI updates and gives a single, reliable count after the DB work.

var selectedIds = dgEmployees.Items.Cast<DataGridItem>()
    .Where(it => {
        var cb = it.FindControl("cbSpriden") as CheckBox;
        return cb != null && cb.Checked;
    })
    .Select(it => (int)dgEmployees.DataKeys[it.ItemIndex])
    .ToList();

// do a single DB call (or a transaction) using selectedIds
// after a successful commit:
lblStatus.Text = selectedIds.Count + " records updated.";

Troubleshooting notes: make sure the accumulator is an integer (not a string) and that you do not append to the label inside the loop; update the label only after the loop/transaction completes. Do not rebind the grid before reading selections on postback (rebinding clears checked state). If the grid uses paging, either persist selections in ViewState/a session collection as pages change or gather ids and post them in a single batch. For DB performance and correctness prefer a batch INSERT or a table-valued parameter instead of many single-row updates.

Checklist: declare the counter/collection outside the loop, collect keys (DataKeys or hidden field), perform DB update in one transaction, set the UI text once using collection.Count. This avoids the "incremental string" symptoms and gives an accurate final count.

Recommended Answers

All 5 Replies

Coudn't you just add a counter to your logic?

[B]int myCounter = 0;[/B]
foreach (DataGridItem spriden_ID in dgEmployees.Items)
{
  CheckBox cbSpriden = (CheckBox) spriden_ID.FindControl("cbSpriden");
  if (cbSpriden.Checked)
  {
    //Stuff to add to db here
    [B]myCounter++;[/B]
  }
  else
  {
    lblStatus.Text ="Scheduling failed: " + addCourses.ErrorMessage;
  }
}

yes i tried that...however when i return the count..for example if i check 3 checkboxes...it will return 123. so it is counting them right...but i only need the 3...hehe. thank you for your response....any other clues?

I'm sorry, I don't understand your reply. There is no way the code above would return the value "123" for the "myCounter" integer. If there are 3 checkboxes, the value would be "3" after the loop completes.

I agree with tgreer, his example would never return "123". The only thing I can think is that you are using a string as your counter variable and concatenating it rather than using an integer and incrementing it. Below is the only feasible code I can think of to duplicate your resuls (example is generic).

string[] arr = new string[]{"a", "b", "c"};
string count = string.Empty;

for (int i = 0;i < arr.length; i++) 
{
     //do something with the string
     
     //update counter
     count += (i + 1);
}

Hi,

can u try this.

int myCounter = 0;
foreach (DataGridItem spriden_ID in dgEmployees.Items)
{
CheckBox cbSpriden = (CheckBox) spriden_ID.cells[index];
if (cbSpriden.Checked)
{
//Stuff to add to db here
myCounter++;
}
else
{
lblStatus.Text ="Scheduling failed: " + addCourses.ErrorMessage;
}
}

Thanks,
Kedar

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.