我在 GridView 中有几个复选框和一个按钮。
我需要计算选中的复选框数,并使用选中的复选框数更新 doTable DB MySQL 的字段计数器。
我试过这个解决方案,但是对于选中的复选框,我在更新中有这个输出,例如已选中 3 个复选框。
counter
1
2
3
这个输出怎么办?
counter
3
3
3
如有任何帮助,我们将不胜感激。
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();
}
}
最佳答案
所以你想用总计数更新行?然后先计算总计数:
int totalCount = GridView1.Rows.Cast<GridViewRow>()
.Count(r => ((CheckBox)r.FindControl("chkSelect")).Checked);
// maybe: if(totalCount > 0)
UpdateProduct(totalCount);
请注意,使用此方法您根本不需要 foreach
。
您需要在文件顶部添加using System.Linq;
。
关于c# - 计算 GridView 中选中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25264066/