65.9K
CodeProject 正在变化。 阅读更多。
Home

在 C# 中管理 DataGrid 的复选框状态

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.50/5 (6投票s)

2006年1月12日

viewsIcon

40577

downloadIcon

191

保持 DataGrid 中的复选框状态

引言

本文演示了使用数组和 Session 来保存 DataGrid 中复选框的状态。

在 ASP.NET 中,DataGrid 可以自动分页。但是,对于每一页上的每个项目,如果 DataGrid 中有复选框,我们如何保持复选框的状态呢?我们可以使用 JavaScript,也可以使用控件来保存选中的复选框索引。以下示例使用 Session 来保存复选框的状态。

第一步是定义一个数组来保存复选框的状态,以及一个变量来存储计数器。

protected int iCounter = -1;
//Then put the status in the array:
{
    iCounter2= (
    {
        iIndex++;
        CheckBox cb=(CheckBox)griditem.Cells[0].Controls[0];
        if(cb.Checked) int check=0;for(int 
            i=0;i<arrayRiderIDs.Length;i++)
            if(iId==arrayRiderIDs[i])if(check==0)else
        {
            {
                {
                    arrayRiderIDs[i]=0;
                }
            }
        }
    }
    for(int i=0;i<arrayRiderIDs.Length;i++)if(iId==arrayRiderIDs[i])
       // after status is saved in array, save the array and counter in 
       //session:<BR>
    Session["arrPersonID"]= iCounter2;
    Session["arrPerson"]= arrayRiderIDs;
    // after you return back to the page, you could use itemcreated to get  
    // status:
    private
    {
        {
            CheckBox cb=
                TableCell cell=e.Item.Cells[0];
            {
                {
                    check=1;
                }
            }
            {
                cb.Checked=
            }
            iCounter++;
            arrayIDs[iCounter]=ID;
            cell.Controls.Add(cb);
        }
    }

所有这些都是服务器端的。

void dgRiders_ItemCreated(object sender,
    System.Web.UI.WebControls.DataGridItemEventArgs e)
if( e.Item.ItemType == ListItemType.Item || e.Item.ItemType == 
    ListItemType.AlternatingItem)
    new CheckBox();
    int ID=(int)dgRiders.DataKeys[e.Item.ItemIndex];
    int check=0;for(int i=0;i<arrayRiderIDs.Length;i++)
        if(ID==arrayRiderIDs[i])if(check==1)true; 
        {
            {
                {
                   check=1;
                }
            }
        }
iCounter2++;
arrayRiderIDs[iCounter2]=iId;

private void dgRiders_ItemCommand(object source, 
    System.Web.UI.WebControls.DataGridCommandEventArgs e)
    if(Session["arrPersonID"]!= null)int) 
        Session["arrPersonID"];
        int iIndex=-1;
        foreach(DataGridItem griditem in dgRiders.Items)
            int iId=arrayIDs[iIndex];
            /* Check the checkbox status, if checked and the checkbox ident is 
            /* not saved in arrayRiderIDs, save to arrayRiderIDs */ 
        protected int[] arrayRiderIDs= new int[20];
© . All rights reserved.