开发者

Dynamic Controls - C# - CheckBoxList Parent - Children

开发者 https://www.devze.com 2023-02-03 18:20 出处:网络
First I understand the need to build dynamic controls in the OnInit Section. However, I read a document from Scott Guthrie?

First I understand the need to build dynamic controls in the OnInit Section.

However, I read a document from Scott Guthrie?

http://scottonwriting.net/sowblog/archive/2004/10/08/162998.aspx

So I got the impression from these blogs that if you add the control to the container then modify the properties, you can get at the control in the Page_Load.

In a nutshell, I have a table with a fk back to the table creating a hierarchy. I load 3 usercontrols the page with checkbox lists that relate back through the parent key.

Table like this:

create table myTbl
(
id   int identity,
par_id int,
item_desc  varchar(25)
other_desc_flag bit
)

What my clients need is the ability to make a checkbox selection. The child set of textboxes will display based on the parent. If the txt_flag is set, a checkbox entry will not be populated. Instead, they want the desc label printed out with a textbox for response. The user data is not kept in the table above by the way.

So the issue I have is these text responses can be at any level of the custom control. So I created a class with a 3 items ( id, literal control, and a textbox ). I then dynamically create the controls based on the selection at any particular level.

I read each level into a dataset, I iterate through the dataset looking for that flag. I capture an index variable in the rows with this flag and I create a List class to hold the id, text_desc. I then remove the row from the table in the dataset and bind the remaining items to the checkboxlist.

I then go back to my control and write out dynamically the controls.

But like all those before me, I am doing evil battle against the Page Cycle...lol.

I cannot see the controls. I plan to DataBind() my controls separately on load as I have not gotten to the point where I'm getting the clients reponses from the database. That's for another day. The placeholder with my dynamic controls is OtherPlaceHolder. I have tried setting the Viewstate to true and false.

Any pointers on how to get the # of items on postback into a session variable so I can create the controls on the OnInit section.

Here is the code. This is being run from a Master Page...

On the controls, I changed the < & > to [ ] because this page that attempts to put code into a controlbox with scrollbars was cutting off that code.

[asp:UpdatePanel ID="UpdPanel" runat="server" EnableViewState="true" UpdateMode="Always"]
[ContentTemplate]
     [asp:Table runat="server" ID="ContainerTbl"]
            [asp:TableHeaderRow]
                 [asp:TableHeaderCell ColumnSpan="2" CssClass="tdCell"][asp:Literal ID="LitDesc" runat="server" Text="Level" /][/asp:TableHeaderCell]
            [/asp:TableHeaderRow]
            [asp:TableRow]
                [asp:TableCell runat="server" ID="tblItems" VerticalAlign="top"]
                    [asp:PlaceHolder runat="server" ID="CtrlPlaceHolder"]
                       [asp:CheckBoxList ID="cboItems"  Visible="false" runat="server" AutoPostBack="true"][/asp:CheckBoxList]
                       [asp:HiddenField ID="otherCnt" runat="server" /]
                    [/asp:PlaceHolder]
                    [asp:PlaceHolder runat="server" ID="OtherPlaceHolder"  EnableViewState="false"]
                    [/asp:PlaceHolder]
                [/asp:TableCell]
           [/asp:TableRow]

            [asp:TableRow]
                [asp:TableCell  VerticalAlign="top"]
                    [asp:Label ID="LabMsg" runat="server" CSSClass="tdCell" Font-Bold="true" Visible="false"/]
                [/asp:TableCell]
            [/asp:TableRow]
        [/asp:Table]
    &nbsp;
        [asp:HiddenField ID="hLevel"  runat="server" Value="" /]

[/ContentTemplate]
[/asp:UpdatePanel]
 private void WriteOut开发者_开发知识库Questions(List<Questions> qList)
    {
        int itemCnt = 1;

        // clear any controls in other place holder first. 
        OtherPlaceHolder.Controls.Clear();
        Table OTD = new Table();
        foreach (Questions qst in qList)
        {
            // we're going to create the new control and add to 
            // the placeholder - OtherPlaceholder
            // we'll then reference those controls and add the data to those
            // controls. 
            // see dynamic control article: http://scottonwriting.net/sowblog/archive/2004/10/08/162998.aspx

            HiddenField hItemId = new HiddenField();
            TextBox txtItem = new TextBox();
            LiteralControl ltcItem = new LiteralControl();
            // add the new controls
            string strItemId = "hItem" + Convert.ToString(itemCnt);
            string strTxtItem = "txtItem" + Convert.ToString(itemCnt);
            string strLtcItem = "ltcItem" + Convert.ToString(itemCnt);
            hItemId.ID = strItemId;
            hItemId.EnableViewState = true;
            txtItem.ID = strTxtItem;
            txtItem.EnableViewState = true;
            ltcItem.ID = strLtcItem;
            ltcItem.EnableViewState = true;
            OTD.Controls.Add(OtherDescAddControl(OtherPlaceHolder, hItemId, ltcItem, txtItem));

            // now reference the new added controls and set values from Question object...

            ++itemCnt;
        }
        OtherPlaceHolder.Controls.Add(OTD);
        // now post data to controls...
        itemCnt = 1;
        foreach (Questions qst in qList)
        {
            string strItemId = "hItem" + Convert.ToString(itemCnt);
            string strTxtItem = "txtItem" + Convert.ToString(itemCnt);
            string strLtcItem = "ltcItem" + Convert.ToString(itemCnt);
            HiddenField hfld = (HiddenField)OtherPlaceHolder.FindControl(strItemId);
            TextBox txtBox = (TextBox)OtherPlaceHolder.FindControl(strTxtItem);
            LiteralControl ltx = (LiteralControl)OtherPlaceHolder.FindControl(strLtcItem);
            hfld.Value = qst.HFld.ToString();
            txtBox.Text = qst.TxtBox;
            txtBox.Attributes.Add("class", "txtBox");
            ltx.Text = qst.Ltc.ToString();
            ++itemCnt;
        }
        //decrement itemCnt and populate box here...
        --itemCnt;
        HiddenField hfldCnt = (HiddenField)CtrlPlaceHolder.FindControl("otherCnt");
        hfldCnt.Value = Convert.ToString(itemCnt);
        hfldCnt.Visible = true;
    }


On the assumption that when you say "I cannot see the controls" you mean that you're getting null references when you try to access them in the postback (rather than that the HTML doesn't contain them), have you tried using Page.EnsureChildControls()?


Ok If I understood your question right, you want to save your controls and load them back on postbacks. Here is what you can do:

List<HiddenField> HiddenFields = new List<HiddenField>{};
List<TextBox> TextBoxs = new List<TextBox>{};
List<LiteralControl> LiteralControls = new List<LiteralControl>{};


OTD.Controls.Add(OtherDescAddControl(OtherPlaceHolder, hItemId, ltcItem, txtItem));
// do this for all your items that you load to page (add them to your list).
HiddenFields.Add(hItemId);
// when you are done with loading all your controls to page, add your populated Lists                        to session. 
Session["HiddenFields"] = HiddenFields;


//On Page_Init or Page_Load, simpy load them back IF **page is postback**.
If(Page.IsPostBack)
{
    LoadControlsFromSession();
}

private void LoadControlsFromSession()
{
    HiddenFields = Session["HiddenFields"] as List<HiddenFields>;
    // Load all your List objects from session like above.
    int counter = 0;
    if(HiddenFields != null)
    {
        foreach(HiddenField hdnField in HiddenFields)
        {
            //load your objects with the same method you have from your List.
            OTD.Controls.Add(OtherDescAddControl(OtherPlaceHolder, HiddenFields[counter], LiteralControls[counter], TextBoxs[counter]));
            counter++;
        }
    }
}


I apologize for lack of clarity.

I believe I did try setting Session variables in my classes when I created the controls and they were null on postback. I tried to access the session variable in the page init and preload and zip.

I did find an interesting workaround to this problem. On page_unload I parsed through the controls into an arraylist of hashtables of the database id & user'sentered text answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消