2011-12-28 105 views
2

我需要在DropDownList的SelectedIndexChanged事件上動態添加CheckBoxList。我已經實現了這一點,但我無法保留其回寄價值。在Asp.Net中檢索動態創建控件的值

這是我迄今所做的:

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)); 
     } 
    } 
} 

回答

4

可能是一個錯字:

CbxList.ID = "Cbx"; 

V.S.

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

偉大的!它工作 – Shah 2011-12-28 13:20:10

+0

Andomar如果我填充複選框列表cbx。我的意思是如果我不把它添加到佔位符。結果會一再重複。我做了 CbxList.Items.Clear();然後我也丟失它的ID,我需要checkboxlist的selecedIndexChange。我被卡住了。你會建議什麼 – Shah 2011-12-30 10:46:52

+0

@ user1057735:只添加項目'if(!IsCallback &&!IsPostBack)'。隨意提出新問題,而不是添加評論;那麼所有的SO都有機會回答! – Andomar 2011-12-30 11:15:14

0

,您可以嘗試在不改變代碼,並使用預先PreRender 只運行你loadTracks()