检索Asp.Net中Post返回上动态创建的控件的值

本文关键字:创建 动态 控件 返回 Asp Net Post 检索 | 更新日期: 2023-09-27 18:19:00

我需要在DropDownList的SelectedIndexChanged事件上动态添加CheckBoxList。我已经做到了这一点,但我无法在回发时保留其值。

到目前为止我所做的是:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    loadTracks();//Needs to generated dynamically
}
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
    loadDegrees();
    }
    loadTracks();
}
public void loadTracks()
{
    try
    {
        ConfigurationDB objConfig = new ConfigurationDB();
        DataSet ds = objConfig.GetTracksByDegreeID(
            Convert.ToInt32(ddlDegree.SelectedValue.ToString()));
        CheckBoxList CbxList = new CheckBoxList();
        CbxList.ID = "Cbx";
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            CbxList.Items.Add(new ListItem(ds.Tables[0].Rows[i]["Track_Name"]
                .ToString(), ds.Tables[0].Rows[i]["ID"].ToString()));
        }
        ph.Controls.Add(CbxList);
        ViewState["tracks"] = true;
    }
    catch(Exception ex)
    {
        Response.Write(ex.Message);
    }
}
//For testing, I added a button and on its click I have added this code
protected void btnDetails_Click(object sender, EventArgs e)
{
    CheckBoxList Cbx = (CheckBoxList)ph.FindControl("chk");
    foreach (ListItem ex in Cbx.Items)
    {
        if (ex.Selected)
        {
            Response.Write(String.Format("You selected: <i>{0}</i> <br>", ex.Value));
        }
    }
}

检索Asp.Net中Post返回上动态创建的控件的值

可能是打字错误:

CbxList.ID = "Cbx";

vs。

CheckBoxList Cbx = (CheckBoxList)ph.FindControl("chk");

您可以尝试不更改代码并使用pre PreRender运行loadTracks()