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

时间:2011-12-28 13:04:19

标签: c# asp.net

我需要在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));
        }
    }
}

2 个答案:

答案 0 :(得分:4)

可能是一个错字:

CbxList.ID = "Cbx";

v.s。

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

答案 1 :(得分:0)

您可以在不更改代码的情况下尝试使用pre PreRender 只运行你loadTracks()