如何从代码后面更新editItemTemplate复选框列表?

时间:2012-10-17 09:02:25

标签: asp.net

我正在使用从SQL数据库提供的gridview。我需要添加一个自定义itemTemplate,它将包含一个从另一个数据源提供的checkboxlist。这是我的xml部分:

        <asp:TemplateField HeaderText="Equipements" >
            <EditItemTemplate>
                <asp:CheckBoxList ID="myCB" runat="server">
                </asp:CheckBoxList>
            </EditItemTemplate>
        </asp:TemplateField>

我正在使用gridview onEditing事件尝试在后面的代码中访问“myCB”:

    protected void OnEditing(object sender, EventArgs e)
    {
        GridView gridview = sender as GridView;
        GridViewEditEventArgs  editEvent = e as GridViewEditEventArgs;
        ListViewItemEventArgs rowEvent = e as ListViewItemEventArgs;
        TableCell equipementsCell = gridview.Rows[editEvent.NewEditIndex].Cells[11];

        CheckBoxList equipements = gridview.Rows.FindControl("myCB") as CheckBoxList;
    }

此代码不起作用,找不到复选框列表。我尝试了许多不成功的事......

1 个答案:

答案 0 :(得分:0)

您应该使用GridView RowDataBound事件:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType  == DataControlRowType.DataRow
    &&  e.Row.RowState == DataControlRowState.Edit)
    {
        CheckBoxList equipements = (CheckBoxList )e.Row.FindControl("myCB"); 
        equipements.DataSource = getSomeData();
        equipements.DataTextField = "TextColumn"; 
        equipements.DataTextField = "IdColumn";
        equipements.DataBind();
    }
}