DataList控件嵌套,激发内部控件事件
DataList控件在嵌套的时候,内部控件都没有事件了,如果想激发事件,需要自己写事件。需要在外部DataList控件的ItemDataBound事件中给内部控件定义事件。但是要在内部控件绑定数据源之前定义。例如现在我有两个嵌套的DataList控件,外部控件ID为DL_DataList,内部控件ID为DL_Item。假如现在有一个已经定义好的DataTable类型的变量 dt。我们在DL_DataList_ItemDataBound事件中写代码如下:
private void DL_DataList_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
{
Control container = e.Item;
ListItemType itemType = e.Item.ItemType;
if (itemType == ListItemType.Item || itemType == ListItemType.Footer || itemType == ListItemType.AlternatingItem)
{
if (e.Item.DataItem == null)
{
return;
}
DataList dlList = (DataList) container.FindControl("DL_Item2");
if (null != dlList)
{
dlList.ItemCommand += new DataListCommandEventHandler(DL_Item2_ItemCommand);
dlList.ItemDataBound += new DataListItemEventHandler(DL_Item2_ItemDataBound);
dlList.DataSource = dt;
dlList.DataBind();
}
}
光这些还不行,我们还要另外定义一个方法,在Page_Load中调用re_Main_PreRender方法,就可以了。{
Control container = e.Item;
ListItemType itemType = e.Item.ItemType;
if (itemType == ListItemType.Item || itemType == ListItemType.Footer || itemType == ListItemType.AlternatingItem)
{
if (e.Item.DataItem == null)
{
return;
}
DataList dlList = (DataList) container.FindControl("DL_Item2");
if (null != dlList)
{
dlList.ItemCommand += new DataListCommandEventHandler(DL_Item2_ItemCommand);
dlList.ItemDataBound += new DataListItemEventHandler(DL_Item2_ItemDataBound);
dlList.DataSource = dt;
dlList.DataBind();
}
}
protected void rp_Main_PreRender(object sender, EventArgs e)
{
foreach (DataListItem item in DL_DataList.Items)
{
DataList rp_Min = (DataList)item.FindControl("DL_Item2");
rp_Min.ItemCommand += new DataListCommandEventHandler(DL_Item2_ItemCommand);
}
}
{
foreach (DataListItem item in DL_DataList.Items)
{
DataList rp_Min = (DataList)item.FindControl("DL_Item2");
rp_Min.ItemCommand += new DataListCommandEventHandler(DL_Item2_ItemCommand);
}
}