从gridview获取多行DataKeys

时间:2012-03-05 20:51:55

标签: asp.net datagridview foreach datakey

目前我有一个Button Click事件,它从Datagrid中的一行(通过复选框)获取DataKey,并将其分配给INT变量以更新databsse中的Individual。当我只检查1个复选框并运行更新时,一切正常。但是我需要用户可以选择所有复选框并选取所有这些Datakeys并将其分配给同一个变量

INT oNewParentID

就像我说的,当只选择1个复选框时,evrything工作正常。我想我正在问如何获取所有Checkbox选择的Uknoiwn数量的Datakeys或所有DataKeys,并将它们存储在上面的Variable中,以便为所有选定的个人运行Update。这是我到目前为止的Button Click事件,它适用于选中的1个复选框:

    protected void imgbtnReassgin_Click(object sender, ImageClickEventArgs e)
{
    foreach (GridViewRow row in gvSalesmanCustomers.Rows)
    {
        CheckBox cb = (CheckBox)row.FindControl("chkSalesCustSelector");
        if (cb != null && cb.Checked)
        {


            int oIndividualID = Convert.ToInt32((gvSalesmanCustomers.DataKeys[row.RowIndex].Value));



            foreach (GridViewRow r in gvSalesmanByManager.Rows)
            {
                CheckBox chkBox = (CheckBox)r.FindControl("chkManagerSalesSelector");
                if (chkBox != null && chkBox.Checked)
                {

                    int oNewParentID = Convert.ToInt32((gvSalesmanByManager.DataKeys[r.RowIndex].Value));



                    Individual ind = new Individual();
                    ind.ReassignIndividual(oIndividualID, oNewParentID);

                    chkBox.Checked = false;
                    cb.Checked = false;

                }


            }



        }


    }

}

她是我的更新存储过程:

CREATE DEFINER=`root`@`%` PROCEDURE `reassign_Individual`(
IN oIndividualID     int(11),
IN oNewParentID         int(11)
)
BEGIN
Update intelliair.individual
set ParentID = oNewParentID
Where IndividualID = oIndividualID;END

My DataGridViews UI

1 个答案:

答案 0 :(得分:0)

重新组织代码。 假设没有理由foreach多次将其分配给最后选择的经理,为第二个ReasignInvidual添加了中断。

protected void imgbtnReassgin_Click(object sender, ImageClickEventArgs e)
{
    List<int> ids = new List<int>();
    foreach (GridViewRow row in gvSalesmanCustomers.Rows)
    {
       CheckBox cb = (CheckBox)row.FindControl("chkSalesCustSelector");
       if (cb != null && cb.Checked)
       {
            int oIndividualID = Convert.ToInt32((gvSalesmanCustomers.DataKeys[row.RowIndex].Value));
            ids.Add(oIndividualID);

            cb.Checked = false;

        }
    }

    int oNewParentID = 0;
    foreach (GridViewRow r in gvSalesmanByManager.Rows)
    {
        CheckBox chkBox = (CheckBox)r.FindControl("chkManagerSalesSelector");
        if (chkBox != null && chkBox.Checked)
        {
             oNewParentID = Convert.ToInt32((gvSalesmanByManager.DataKeys[r.RowIndex].Value));
             chkBox.Checked = false;
             break; //no reason to go with the same logic to next records
             //if you want to uncheck all the checkboxes continue with specific code just for that purpose
        }
    } 


   if (ids.Count > 0 && oNewParentID > 0)
        foreach(var id in ids)
        {
            Individual ind = new Individual();
            ind.ReassignIndividual(id, oNewParentID);
        }

}