C# 如何动态生成TextBox 控件。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2229019/
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-07 00:34:00  来源:igfitidea点击:

How to dynamically generate a TextBox control.

c#asp.nettextbox

提问by Innova

How does one dynamically generate a TextBox control at run-time as a result of a button click? For each button click, I would like to create a TextBox control along with corresponding dynamic labels. I would like to do this within ASP.NET using the C# language.

作为按钮单击的结果,如何在运行时动态生成 TextBox 控件?对于每个按钮单击,我想创建一个 TextBox 控件以及相应的动态标签。我想使用 C# 语言在 ASP.NET 中执行此操作。

采纳答案by rahul

TextBox txt = new TextBox();
txt.ID = "textBox1";
txt.Text = "helloo";
form1.Controls.Add(txt);

Label lbl = new Label();
lbl.Text = "I am a label";
form1.Controls.Add(lbl);

回答by David_001

The following will create the controls:

以下将创建控件:

var newTextbox = new Textbox();   
var newLabel = new Label();

you can then set the properties etc that you want.

然后,您可以设置所需的属性等。

Then find somewhere on your page to add them to, say you have a panel called panel1, then do the following:

然后在您的页面上找到某个地方将它们添加到,假设您有一个名为 panel1 的面板,然后执行以下操作:

panel1.Controls.Add(newTextbox);
panel1.Controls.Add(newLabel);

However, doing this will not work after postback - you need to recreate the dynamic controls yourself on a postback.

但是,在回发后这样做将不起作用 - 您需要在回发时自己重新创建动态控件。

Say you have the following page:

假设您有以下页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

When you do a postback, only the controls that are defined in the above page will be generated for you. Controls you have dynamically added need to be re-created by you (for example in the Page_Load).

当您进行回发时,只会为您生成在上述页面中定义的控件。您动态添加的控件需要由您重新创建(例如在 Page_Load 中)。

To do this, the simplest way is to remember the total number of controls you have added in the viewstate, then add that many controls back in when a postback occurs.

要做到这一点,最简单的方法是记住您在视图状态中添加的控件总数,然后在发生回发时重新添加这么多控件。

The following should get you started:

以下应该让你开始:

using System;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Add any controls that have been previously added dynamically
            for (int i = 0; i < TotalNumberAdded; ++i)
            {
                AddControls(i + 1);
            }

            // Attach the event handler to the button
            Button1.Click += new EventHandler(Button1_Click);
        }

        void Button1_Click(object sender, EventArgs e)
        {
            // Increase the number added and add the new label and textbox
            TotalNumberAdded++;
            AddControls(TotalNumberAdded);
        }

        private void AddControls(int controlNumber)
        {
            var newPanel = new Panel();
            var newLabel = new Label();
            var newTextbox = new TextBox();

            // textbox needs a unique id to maintain state information
            newTextbox.ID = "TextBox_" + controlNumber;

            newLabel.Text = "New Label";

            // add the label and textbox to the panel, then add the panel to the form
            newPanel.Controls.Add(newLabel);
            newPanel.Controls.Add(newTextbox);
            form1.Controls.Add(newPanel);
        }

        protected int TotalNumberAdded
        {
            get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
            set { ViewState["TotalNumberAdded"] = value; }
        }

    }
}

回答by emremrah

To add multiple controls as you asked, use a for loop:

要按照您的要求添加多个控件,请使用 for 循环:

for (int i = 0; i < 2; ) {
    TextBox textBox = new TextBox();
    textBox.Text = "Hi";
    textBox.Name = "textBox" + i.ToString();
    form2.Controls.Add(textBox);
}

But the controls (textboxes) overlaps. You need to organize their locations.

但是控件(文本框)重叠。你需要组织他们的位置。

EDIT:E.g

编辑:例如

TextBox txt = new TextBox();
txt.Location = new Point(500, 100);

回答by Kiran G

The code below shows how to print a label and text box according to the value selected in the dropdownlist. The two placeholders are used so that they can be appropriately placed in two different table divisions

下面的代码显示了如何根据下拉列表中选择的值打印标签和文本框。使用了两个占位符,以便它们可以适当地放置在两个不同的表格分区中

            int numlabels = System.Convert.ToInt32(ddlNumOfVolunteers.SelectedItem.Text);
            for (int i = 1; i <= numlabels; i++)
            {
                Label myLabel = new Label();
                TextBox txtbox = new TextBox();
                // Set the label's Text and ID properties.
                myLabel.ID = "LabelVol" + i.ToString();
                myLabel.Text = "Volunteer " + i.ToString();
                txtbox.ID = "TxtBoxVol" + i.ToString();
                PlaceHolder1.Controls.Add(myLabel);
                PlaceHolder2.Controls.Add(txtbox);
                // Add a spacer in the form of an HTML <br /> element.
                PlaceHolder2.Controls.Add(new LiteralControl("<br />"));
                PlaceHolder1.Controls.Add(new LiteralControl("<br />"));

回答by KevinAgastra21

Well I would suggest you to firstcreate a grid and to specify the wanted number of rows and columns, in order to have everything organized.

好吧,我建议您首先创建一个网格并指定所需的行数和列数,以便组织所有内容。

Your MainWindow.xamlshould look like this:

您的MainWindow.xaml应如下所示:

 <TabItem.Background>
                <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                    <GradientStop Color="#FFF0F0F0" Offset="1"/>
                    <GradientStop Color="#FF111111"/>
                    <GradientStop Color="#FF4F2B2B" Offset="0.946"/>
                </LinearGradientBrush>
            </TabItem.Background>

            <ScrollViewer HorizontalScrollBarVisibility="Visible" Margin="0,-1,0,2">

   <Grid Name="gridaxis"  x:FieldModifier="private" >
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />

                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                </Grid>


            </ScrollViewer>

        </TabItem>

Nextwe are trying to build two rows of textboxes which will be dynamically created on runtime. By using two different buttons, one for the first row textboxes and the other for the second row, we will be able to spawn the desired textboxes.

接下来,我们尝试构建两行文本框,这些文本框将在运行时动态创建。通过使用两个不同的按钮,一个用于第一行文本框,另一个用于第二行,我们将能够生成所需的文本框。

 int i = 0;
    private void add_in_grid(object sender, RoutedEventArgs e)
    {
        i = i + 1;
        System.Windows.Controls.TextBox newDepo = new System.Windows.Controls.TextBox();

        newDepo.Name = "new_Depo_" + i;
        newDepo.Text = "neue Depo" + i;

        newDepo.Width = 200;
        newDepo.Height = 200;

        Grid.SetColumn(newDepo, i);
        Grid.SetRow(newDepo, 1);

        gridaxis.Children.Add(newDepo);
    }

    int k = 0;
    private void add_row_depo(object sender, RoutedEventArgs e)
    {
        k = k + 1;
        System.Windows.Controls.TextBox newRowDepo = new System.Windows.Controls.TextBox();
        newRowDepo.Name = "newRowDepo" + k;
        newRowDepo.Text = "row depo" + k;



        newRowDepo.Width = 200;
        newRowDepo.Height = 200;

        Grid.SetColumn(newRowDepo, k);
        Grid.SetRow(newRowDepo, 2);
        gridaxis.Children.Add(newRowDepo);
    }

I hope it is clear enough. You just have to add one button for each of the two methods listed above. Just like this:

我希望它足够清楚。您只需为上面列出的两种方法中的每一种添加一个按钮。像这样:

 <Button x:Name="grid_textbox" Content="add using grid" Click="add_in_grid" HorizontalAlignment="Left" Margin="802,537,0,0" VerticalAlignment="Top" Width="197" Height="60"/>
    <Button x:Name="rowgrid" Content="add row" Click="add_row_depo" HorizontalAlignment="Left" Margin="617,537,0,0" VerticalAlignment="Top" Width="159" Height="65"/>