Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在GridView中计数选中的复选框_C#_Asp.net_Checkbox - Fatal编程技术网

C# 在GridView中计数选中的复选框

C# 在GridView中计数选中的复选框,c#,asp.net,checkbox,C#,Asp.net,Checkbox,我在GridView中有几个复选框和一个按钮 我需要计算选中的复选框数,并使用doTable DB MySQL的字段计数器中选中的复选框数进行更新 我尝试了此解决方案,但对于选中的复选框,我在更新中有此输出,例如,选中了3个复选框 counter 1 2 3 如何处理此输出 counter 3 3 3 任何帮助都将不胜感激 protected void btnUpdate_Click(object sender, EventArgs e) { int counter = 0;

我在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();
    }      
}

您需要推迟对
UpdateProduct
的调用。你说得太早了。试试这个:

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

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

// Call this now.
UpdateProduct(counter);

那么您想用总计数更新行吗?然后首先计算总计数:

int totalCount = GridView1.Rows.Cast<GridViewRow>()
    .Count(r => ((CheckBox)r.FindControl("chkSelect")).Checked);
// maybe: if(totalCount > 0)
UpdateProduct(totalCount);
int totalCount=GridView1.Rows.Cast()
.Count(r=>((复选框)r.FindControl(“chkSelect”)).Checked);
//可能:如果(totalCount>0)
UpdateProduct(totalCount);
注意,使用这种方法根本不需要foreach的
foreach


您需要使用System.Linq添加
位于文件顶部。

您能描述一下当您尝试运行上述代码时会发生什么情况吗?