I need to get value on button click from dynamic control which was generated on Page

前端 未结 1 1846
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 10:07

There have many controls are Generated I want to save value on button click which is dynamically generated on page,Can any one Help me to this. I am new in this field so i m

相关标签:
1条回答
  • 2020-12-11 10:50

    Here a complete demo snippet how to handle creating and reading values from dynamic controls. You can then adapt it to your own needs.

    protected void Page_Load(object sender, EventArgs e)
    {
        createDynamicControls();
    }
    
    public void createDynamicControls()
    {
        //add a textbox
        TextBox tb = new TextBox();
        tb.ID = "DynamicTextBox";
        tb.Text = "TextBox Content";
        PlaceHolder1.Controls.Add(tb);
    
        //add a dropdownlist
        DropDownList drp = new DropDownList();
        drp.ID = "DynamicDropDownList";
        drp.Items.Insert(0, new ListItem("Value A", "0", true));
        drp.Items.Insert(1, new ListItem("Value B", "1", true));
        PlaceHolder1.Controls.Add(drp);
    
        //add a button
        Button btn = new Button();
        btn.Text = "Submit Dynamic Form";
        btn.Click += Button1_Click;
        PlaceHolder1.Controls.Add(btn);
    }
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        //find the dynamic controls again with findcontrol
        TextBox tb = FindControl("DynamicTextBox") as TextBox;
        DropDownList drp = FindControl("DynamicDropDownList") as DropDownList;
    
        //visualize the values
        Label1.Text = tb.Text + "<br>";
        Label1.Text += drp.SelectedItem.Text;
    }
    

    The aspx

    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    <br />
    <br />
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    
    0 讨论(0)
提交回复
热议问题