如何使动态添加/删除控件的功能 [英] How to make function for dynamicly add/remove controls

查看:62
本文介绍了如何使动态添加/删除控件的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何制作动态添加/删除控件的功能,如图像预览:



图像链接



我想在每个字段旁边放置一个按钮,添加新字段和按钮,如同我上面附上的图片预览?



我尝试过:



如何制作动态添加/删除控件的功能

How to make function for dynamicly add/remove controls, something like the image preview:

Link for the image

I want to put a button, add new field, and a buttons to remove next to every field as in the image preview which i attach above?

What I have tried:

How to make function for dynamicly add/remove controls

推荐答案

试试这个



try this

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <ul id="ul1"> </ul>
    <a href="#" onclick="add()" style="color:green;text-decoration:none">Add new</a>
    <script>
        function add() {
            var li = document.createElement('li');
            li.innerHTML = '<select><option>Select</option></select> <a  href="#" onclick="remov(this)"  style="color:red;text-decoration:none">&times;</a>'
            document.getElementById('ul1').appendChild(li);
        }
        function remov(obj)
        {
            obj.parentElement.remove()
        }
    </script>
</body>
</html>


从未对此进行测试,但您可以尝试以下方法:



Never tested on this, but you could try something like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        int occurence =1;
        ViewState["Counter"] = occurence;
        LoadUserControl();
    }

}

protected void Button1_Click(object sender, EventArgs e)
{
    if(ViewState["Counter"] != null){
       int count = Convert.ToInt32(ViewState["Counter"]);
       ViewState["Counter"] = count + 1;
       LoadUserControl();
    }
}

protected void LoadUserControl()
{
    int count = Convert.ToInt32(ViewState["Counter"]);
    if (count > 0)
    {
        for (int i = 0; i < count; i++)
        {
            WebUserControl uc = (WebUserControl)Page.LoadControl("WebUserControl.ascx");
            webUC.ID = "webUC" + i.ToString();
            //add the user control in the form
            //note that you can also add them in a PlaceHolder or Panel control
            form1.Controls.Add(uc);
        }
    }
}





请记住,上面的代码是只是一个简单的示例,因此在使用ViewState时要小心,以避免页面性能问题。此外,ViewState在尺寸方面有限制,因此请确保您不会在其中存储大量数据。



我还建议您使用阅读动态控件创建和页面循环事件。



HTH



Keep in mind that the code above is just a quick example, so be careful when using ViewState to avoid page performance issue. Also ViewState has a limit when it comes to size, so make sure that you don't store a huge amount of data in it.

I would also suggest you to read on Dynamic Controls creation and Page cycle events.

HTH


这篇关于如何使动态添加/删除控件的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆