How do I remove my dynamically added textbox?

后端 未结 2 1546
终归单人心
终归单人心 2021-01-22 14:11

here in my codebehind I have created a way to add asp:Textbox dynamically

Create button action to create text field

List contr         


        
2条回答
  •  时光说笑
    2021-01-22 14:53

    You'll need to have your data wrapped in an Update Panel, otherwise every time your page has to go to the server a Postback will occur. That way when your logic hits the server, your remove logic can indeed execute without the Postback.

    You could also simply set the control visibility to false.

    Another possibility would be to do a large chunk of this via the Client, which would be as simple as .hide(); or .show(); with jQuery.

    Also keep in mind your approach will create difficulties in maintaining the View State. Another issue with the proposed solution, an Update Panel stores the page in memory then recreates it via Ajax.

    would be what you need to avoid a Postback.

    Honestly you could do it quite simply like:

    ... btnRemoveTextbox_Click(..., ...)
    {
         txtDynamic.Visibility = false;
    }
    

    As I said, though you can do this with the server you may be better off with Client Side then call, a Service.

    Important: If those are your Event Handler names, you shouldn't have both be identical when you have two separate task designed for them.


    Update/Example

    // Front-End:
    
    
        
            
            
            
        
    
    
    // Backend:
    protected void btnCreateText_Click(object sender, EventArgs e)
    {
        var text = new TextBox();
        text.ID = "txtDynamic";
    
        plhControl.Controls.Add(text);
    
    }
    
    protected void btnRemoveText_Click(object sender, EventArgs e)
    {
        var text = new TextBox();
        text.ID = "txtDynamic";
        text.Visible = false;
    }
    

    And that actually works, I just tried it. One thing to note here, you need to ensure you have a valid id and populate the proper control.

    This code is incredibly rough, it wouldn't be wise for production because it works for a control that has that single Id or contain validation. You would need to loop through the controls, ensure the proper Id is detected and exist before attempting to remove. You'll need to debug your code and validate.

提交回复
热议问题