none
求助如何实现动态生成控件,然后获取值 RRS feed

  • 问题

  • 现在项目需要一个动态生成表单的功能

    我一开始的实现如下

    .aspx文件生成表单代码块

    <table>
    
                <asp:Repeater ID="BrandList" runat="server">
                    <ItemTemplate>
                        <tr>
                            <th>
                             <%#Eval("t_name") %>:
                            </th>
                                              <td>
                          <%#Eval("TypeName")%> : <%#out_table(int.Parse(Eval("Id").ToString()),
                          Eval("t_name").ToString(),Eval("inputType").ToString(),
                          Eval("xuanxiang").ToString(),
                          int.Parse(Eval("required").ToString()))%>
                            </td>
     
                        </tr>
                    </ItemTemplate>
                </asp:Repeater>
        </table>


    .aspx.cs文件生成表单代码块

     protected void Page_Load(object sender, EventArgs e)
        {
            
            thisGod = this;
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["id"].ToString()))
                {
                    //int TypeId = setid();
                    //box.TypeId = TypeId;
                    //box.createTime = DateTime.Now;
                    string wheresql = "TypeId = " + TypeId.ToString();
                    this.BrandList.DataSource = DAL.tableType.GetList(wheresql);
                    this.BrandList.DataBind();
                }
            }
        }
    
        public string out_table(int ControlId, string t_name, string inputType, string xuanxiang,int required)
        {
            box.List.Add(new tableBase() { name = (t_name +"_"+ ControlId.ToString()),Value  = "",ControlId = ControlId});
            string inputstring = "";
            if (inputType == "text")
            {
                inputstring = "<input id=\"" + t_name + "_" + ControlId + "\""  + " type=\"text\" runat=\"server\" ";
                if (required == 1) 
                {
                    inputstring += "required=\"required\" ";
                }
                inputstring += "/>";
                
            }
            if (inputType == "textarea")
            {
                inputstring = "<textarea  id=\"" + t_name + "_" + ControlId + "\"" + " type=\"text\" runat=\"server\" ";
                if (required == 1)
                {
                    inputstring += "required=\"required\" ";
                }
                inputstring += "style=\"width: 300px; height: 200px\" ></textarea> ";
            }
            if (inputType == "select")
            {
                inputstring = "<select id=\"" + t_name +  "_" + ControlId + "\""  + " runat=\"server\" ";
                if (required == 1)
                {
                    inputstring += "required=\"required\" "; 
                }
                inputstring += "/>";
                string[] split = xuanxiang.Split(new Char[] { '|' });
                foreach (string s in split)
                {
    
                    if (s.Trim() != "")
                        inputstring += "<option value=\"" + s + "\">" + s + "</option> ";
    
                    
                }
                inputstring += "</select>";
            }
                return inputstring;
            
        }


    .aspx提交表单按键代码块

    <asp:Button ID="Button1" runat="server" Text="确定" OnClick="Button1_Click" />


    .aspx.cs提交表单按键代码块

      protected void Button1_Click(object sender, EventArgs e)
        {
            //System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection(Request.Form);
            //nc.GetValues("111_1")[0].ToString();
            //Request.Form.GetValues("111_1");
            //Request.Form.GetValues("222_2");
            //Request.Form.GetValues("333_3");
            //Request.Form.GetValues("55_4");   
    
            getAllControlValue(this);
            //SetTable_mg();
        }
    
      Hashtable getAllControlValue(object PageOrUserControl)
        {
            Hashtable rtn = new Hashtable();
    
            foreach (Control ctr in (PageOrUserControl as Page).Controls)
            {
                getControlValue(ctr, rtn);
            }
            Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('已提交')</script>");
            return rtn;
        }
        void getControlValue(Control ctrIn, Hashtable ht)
        {
            DateTime Date = DateTime.Now;
            foreach (Control ctr in ctrIn.Controls)
            {
                int ControlId = 0;
                string value = "";
                Type controlType = ctr.GetType();
    
                switch (controlType.ToString())
                {
                    case "System.Web.UI.HtmlControls.HtmlInputText":
                        HtmlInputText controlTextObj = (HtmlInputText)ctr;
                        ControlId = GetControlId(controlTextObj.ID);
                        value = controlTextObj.Value;
                        break;
                    case "System.Web.UI.HtmlControls.HtmlTextArea":
                        HtmlTextArea controlAreaObj = (HtmlTextArea)ctr;
                        ControlId = GetControlId(controlAreaObj.ID);
                        value = controlAreaObj.Value;
                        break;
                    case "System.Web.UI.HtmlControls.HtmlSelect":
                        HtmlSelect controlSelectObj = (HtmlSelect)ctr;
                        ControlId = GetControlId(controlSelectObj.ID);
                        value = controlSelectObj.Value;
                        break;
                    //case "其他类型":
                    //    其它类型 controlTextBoxObj = (其它类型)ctr;
                    //    string controlTextBoxName = controlTextBoxObj.ID;
                    //    string controlTextBoxValue = controlTextBoxObj.Text;
                    //    ht.Add(controlTextBoxName, controlTextBoxValue);
                    //    break;
                    default:
                        break;
                }
                if (ControlId != 0)
                {
                    Model.table_mg model = new Model.table_mg();
                    model.ControlId = ControlId;
                    model.t_Value = value;
                    model.createTime = Date;
                    DAL.table_mg.Add(model);
                }
            }
            
        }

    经过调试发现无法获得动态生成控件(HtmlText,HtmlSelect,HtmlArea)里的Value

    于是查看msdn文档:

    如何:以编程方式向 ASP.NET 网页添加控件

    PlaceHolder 类

    Control.Controls 属性

    BaseDataList.SelectedIndexChanged 事件

    复制上面几个文档里的代码写了如下的测试小程序

    aspx.cs生成动态控件代码

     <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
                <asp:ListItem>1</asp:ListItem>
                <asp:ListItem>2</asp:ListItem>
                <asp:ListItem>3</asp:ListItem>
            </asp:DropDownList>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

    aspx.cs动态生成控件代码

            protected void DropDownList1_SelectedIndexChanged(object sender,System.EventArgs e)
            {
                //DropDownList DropDownList1 = new DropDownList();
                //PlaceHolder PlaceHolder1 = new PlaceHolder();
    
                // Get the number of labels to create.
                int numlabels = System.Convert.ToInt32(this.DropDownList1.SelectedItem.Text);
                for (int i = 1; i <= numlabels; i++)
                {
                    Label myLabel = new Label();
    
                    // Set the label's Text and ID properties.
                    myLabel.Text = "Label" + i.ToString();
                    myLabel.ID = "Label" + i.ToString();
                    this.PlaceHolder1.Controls.Add(myLabel);
                    // Add a spacer in the form of an HTML <br /> element.
                    this.PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
                }
            }
    

    aspx获取动态控件代码

     <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

    aspx.cs获得动态控件代码

     protected void Button1_Click(object sender, EventArgs e)
            {
                getAllControlValue(this);
            }
    
            Hashtable getAllControlValue(object PageOrUserControl)
            {
                Hashtable rtn = new Hashtable();
    
                foreach (Control ctr in (PageOrUserControl as Page).Controls)
                {
                    getControlValue(ctr, rtn);
                }
    
                return rtn;
            }
    
            void getControlValue(Control ctrIn, Hashtable ht)
            {
                //foreach (Control ctr in ctrIn.Controls)
                foreach (Control ctr in this.PlaceHolder1.Controls)
                {
                    Type controlType = ctr.GetType();
    
                    switch (controlType.ToString())
                    {
                        case "System.Web.UI.WebControls.Label":
                            Label LabelObj = (Label)ctr;
                            string LabelName = LabelObj.ID;
                            string LabelText = LabelObj.Text;
                            break;
                        //case "System.Web.UI.HtmlControls.HtmlInputText":
                        //    HtmlInputText controlInputTextObj = (HtmlInputText)ctr;
                        //    string controlInputTextName = controlInputTextObj.ID;
                        //    string controlInputTextValue = controlInputTextObj.Value;
                        //    ht.Add(controlInputTextName, controlInputTextValue);
                        //    break;
                        //case "System.Web.UI.HtmlControls.HtmlTextArea":
                        //    HtmlTextArea controlHtmlAreaObj = (HtmlTextArea)ctr;
                        //    string controlHtmlAreaName = controlHtmlAreaObj.ID;
                        //    string controlHtmlAreaValue = controlHtmlAreaObj.Value;
                        //    ht.Add(controlHtmlAreaName, controlHtmlAreaValue);
                        //    break;
                        //case "System.Web.UI.HtmlControls.HtmlSelect":
                        //    HtmlSelect controlHtmlSelectObj = (HtmlSelect)ctr;
                        //    string controlHtmlSelectName = controlHtmlSelectObj.ID;
                        //    string controlHtmlSelectValue = controlHtmlSelectObj.Value;
                        //    ht.Add(controlHtmlSelectName, controlHtmlSelectValue);
                        //    break;
                        //case "其他类型":
                        //    其它类型 controlTextBoxObj = (其它类型)ctr;
                        //    string controlTextBoxName = controlTextBoxObj.ID;
                        //    string controlTextBoxValue = controlTextBoxObj.Text;
                        //    ht.Add(controlTextBoxName, controlTextBoxValue);
                        //    break;
                        default:
                            break;
                    }
                }
            }

    但是经过调试,发现在生成阶段PlaceHolder控件里的Controls里面Count是有数值的,但是当代码进行到获取阶段PlaceHolder控件里的Controls里面Count变成0

    我想求助,大家,如何改进代码获取动态生成控件的value值,,

    2014年7月25日 10:28

全部回复

  • 你好,

    因为你每次点击button,会发生postback,而你的动态控件数据会丢失。

    所以每次,你会发现controls的Count为0.

    当你把创建动态控件的过程放在

    protected override void OnInit(EventArgs e)
    {

        createDynamicControl();//在OnInit中执行动态添加控件的方法,这样就会保存其状态视图

    你可以参考下面的链接

    http://www.cnblogs.com/vihone/archive/2010/01/06/1640025.html

    2014年7月29日 2:43