C# 如何在asp.net中单击按钮时动态添加控件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18914357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:34:56  来源:igfitidea点击:

How to add controls dynamically when click button in asp.net?

c#asp.net

提问by user2500094

I'm trying to add controls dynamically

我正在尝试动态添加控件

Code:

代码:

AddVisaControl.ascx

添加VisaControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %>
<%@ Register assembly="BasicFrame.WebControls.BasicDatePicker" namespace="BasicFrame.WebControls" tagprefix="BDP" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
<tr>
  <td class="style8"> Visa Number:</td>
  <td class="style20"><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
  <td class="style22"> Country Name:</td>
  <td class="style23">
<asp:DropDownList ID="dropCountry" Width="165px" runat="server">
</asp:DropDownList></td>
</tr>
 <tr>
 <td class="style22"> Type of Visa:</td>
 <td class="style23">
<asp:DropDownList ID="dropVisa" Width="165px" runat="server"> </asp:DropDownList></td>
<td class="style22"> Type of Entry:</td>
<td class="style23">
<asp:DropDownList ID="dropEntry" Width="165px" runat="server"> </asp:DropDownList></td>
</tr>
<tr>
<td class="style8">&nbsp; Expiry Date</td>
<td class="style20">
</td>
</tr>
</table>

.cs code:

.cs 代码:

Below code is the problem when the first time I click add button it is adding controls properly but If I close the browser window and comes again and click the add button I got more controls

下面的代码是我第一次单击添加按钮时的问题,它正在正确添加控件,但是如果我关闭浏览器窗口并再次单击添加按钮,我将获得更多控件

   static int i = 0;
    protected void addnewtext_Click(object sender, EventArgs e)
    {
        i++;
        for (int j = 0; j <= i; j++)
        {
            AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");
            PlaceHolder1.Controls.Add(ac);
            PlaceHolder1.Controls.Add(new LiteralControl("<BR>"));
        }
    }

In the below image If I click add more visa button I want to get another visa details

在下图中,如果我点击添加更多签证按钮,我想获得另一个签证详细信息

enter image description here

在此处输入图片说明

Any ideas? Thanks in advance

有任何想法吗?提前致谢

回答by Sajith

I will show one examples you can try it your own way

我将展示一个示例,您可以按自己的方式尝试

An idea would be to create a list of buttons in which you'd store the buttons you created inbtnCreateDynamic_click

一个想法是创建一个按钮列表,您可以在其中存储您创建的按钮btnCreateDynamic_click

you could have a method like:

你可以有一个方法,如:

private Button CreateButton(string id, string name)
        {
            Button b = new Button();
            b.Text = name;
            b.ID = id;
            b.Click += new EventHandler(Button_Click);
            b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
            return b;
        }

in btnCreateDynamic_clickyou could have something like:

btnCreateDynamic_click你可能有这样的事情:

Button b = CreateButton("dinamicBtn"+myDinamicButtonsList.Count.ToString(),"dinamicBtn"+myDinamicButtonsList.Count.ToString());
myDinamicButtonsList.add(b);
and in the pageLoad for example you could do something like

foreach(button btn in myDinamicButtonsList){
    form1.Controls.Add(btn));
}

List<Button> myDinamicButtonsList = new List<Button>();

myDinamicButtonsListshould be stored somewhere from where it could be retrieved after each request.

myDinamicButtonsList应该存储在每次请求后可以检索的地方。

EDIT: In page load you could have something like this:

编辑:在页面加载中,你可以有这样的东西:

if(Session["myDinamicButtons"] == null){
    List<Button> myDinamicButtonsList = new List<Button>();
    Session["myDinamicButtons"] = myDinamicButtonsList;
}

foreach(Button btn in Session["myDinamicButtons"] as List<Button>){
    form1.Controls.Add(btn));
}

i didn't tested it but it should work.

我没有测试它,但它应该工作。

also put on some information following may more help..

还提供了一些以下信息可能会更有帮助..

Your button click event at the client will cause a page postback that will start the ASP.Net Page Life-cycle. enter image description here

您在客户端的按钮单击事件将导致将启动 ASP.Net 页面生命周期的页面回发。 在此处输入图片说明

Your button click event on the server is a PostBackEventand you should be able to use the same method call CreateMyButton()that you used in the Load or Init events.

您在服务器上的按钮单击事件是 a PostBackEvent,您应该能够CreateMyButton()使用在 Load 或 Init 事件中使用的相同方法调用。

回答by Rameez Ahmed Sayad

Remove static int i = 0;

消除 static int i = 0;

Change the method as below

更改方法如下

  protected void addnewtext_Click(object sender, EventArgs e)
    {     

            AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");
            PlaceHolder1.Controls.Add(ac);
            PlaceHolder1.Controls.Add(new LiteralControl("<BR>"));

    }

回答by Menelaos Vergis

if you remove the static 'i' variable and use a hidenInput to maintain the no of created controls (or a session value) you will be fine.

如果您删除静态 'i' 变量并使用 hidenInput 来维护已创建控件的数量(或会话值),您会没事的。

But I suggest you read the following article to find a better way of creating dynamic controls :

但我建议您阅读以下文章以找到创建动态控件的更好方法:

Dynamic control creation in ASP.NET

ASP.NET 中的动态控件创建