0

datalist 在运行时生成代码:如何在页面回发后访问 datalist 元素的值?

void CreateDATELIST(Control container)
{   
    var st = settings.CustomPossition();
    foreach (var item in settings.CustomPossition())
    {  
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Possition");
        dt.Columns.Add("Production");
        dt.Columns.Add("dpo");
        dt.Columns.Add("WorkDay");
        DataRow dr;
        foreach (var users in item.Users)
        {
            dr = dt.NewRow();
            dr["Name"] = users.Name;
            dr["Possition"] = users.Position.Name;
            dr["Production"] = users.DailyGoalAmount * (double)(users.WorkDays / 12;
            dr["dpo"] = users.DailyGoalAmount;
            dr["WorkDay"] = users.WorkDays;
            dt.Rows.Add(dr);
            dt.AcceptChanges();
        }
        DataList dataList = new DataList();
        dataList.ItemTemplate = Page.LoadTemplate("Commnets.ascx");
        container.Controls.Add(dataList);

        dataList.DataSource = dt;
        dataList.DataBind();
    }
}
4

2 回答 2

0

如果您分配Id给您DataList创建的动态,如下所示:

DataList dataList = new DataList();
dataList.ID = "dlstUser";

然后:使用您在模板用户控件中拥有的任何控件和 ID 更改控件 ID,c.FindControl("lblName")并在按钮单击或任何您想要datalist.

DataList dataList = pnlDataList.FindControl("dlstUser") as DataList;
foreach (DataListItem dli in dataList.Items)
{
    ControlCollection controls = dli.Controls;
    foreach (Control c in controls)
    {
        Label lblName = c.FindControl("lblName") as Label;
    }
}
于 2012-12-01T13:23:20.700 回答
0

您可以只订阅 DataList 的ItemDataBound事件。

DataList dataList = new DataList();
dataList.ItemDataBound += dataList_ItemDataBound;

在事件处理程序中:

void dataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
      var item = e.Item.DataItem as DataRowView;
}
于 2012-12-01T13:32:38.273 回答