Hamamelis Hamamelis - 1 month ago 6
ASP.NET (C#) Question

Count checked checkboxes in a GridView

I have several checkboxes and a button inside a GridView.

I need count the checkboxes selected and update with this number of checkboxes selected the field counter of the doTable DB MySQL.

I tried this solution but for the checkboxes selected I have this output in update, e.g. 3 checkboxes selected.

counter
1
2
3


How to do for this output?

counter
3
3
3


Any help would be appreciated.

protected void btnUpdate_Click(object sender, EventArgs e)
{
int counter = 0;

foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkSelect") as CheckBox);

if (chkRow.Checked)
{
counter = counter + 1;
UpdateProduct(counter);

}
}


private void UpdateProduct(int counter)
{
string sql = String.Format(@"Update doTable set
counter = {0}; ",
counter.ToString());
try
{
conn.Open();
OdbcCommand cmd = new OdbcCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
}
}

Answer

So you want to update the rows with the total-count? Then calculate the total-count first:

int totalCount = GridView1.Rows.Cast<GridViewRow>()
    .Count(r => ((CheckBox)r.FindControl("chkSelect")).Checked);
// maybe: if(totalCount > 0)
UpdateProduct(totalCount);

Note that you don't need the foreach at all with this approach.

You need to add using System.Linq; at the top of the file.