如何在后面的c#中以编程方式创建一个asp:button(没有点击处理)

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

How to create an asp:button programmatically in c# behind (without click handling)

c#asp.netbuttonaspbutton

提问by dudledok

The following button provides the exact functionality I require, but it must be done programmatically as I will be making more than one based on some variables, but the latter I can figure out if I can just create the button below as a starter:

以下按钮提供了我需要的确切功能,但必须以编程方式完成,因为我将根据某些变量制作多个,但后者我可以弄清楚我是否可以创建下面的按钮作为启动器:

<asp:Button runat="server" OnCommand="Load_Items" CommandArgument="1" text="Submit" />

More information on what I've been doing here.

有关我在这里所做的工作的更多信息。

Edit:

编辑:

I have looked at questions like this, but don't see where to go from Button btnSave = new Button();to seeing a button on the page. Also, most questions I've found seem to go about using C# to handle clicking, but I want to have an OnCommand property to handle it.

我已经看过的问题是这样的,但看不出从哪里去Button btnSave = new Button();看到页面上的按钮。此外,我发现的大多数问题似乎都与使用 C# 处理点击有关,但我希望有一个 OnCommand 属性来处理它。

If I do the following and search using the developer tools for "btn", I get no results.

如果我执行以下操作并使用开发人员工具搜索“btn”,则不会得到任何结果。

Button btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save";
btnSave.CssClass = "btn";

采纳答案by Win

Here is how you create a Button with Command event.

以下是如何使用命令事件创建按钮。

Once it is created, you need to find a way of displaying it. The following example uses PlaceHolder; you can also substitute with Panelif you want.

创建后,您需要找到一种显示方式。以下示例使用 PlaceHolder; Panel如果你愿意,你也可以替换。

ASPX

ASPX

<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>

Code Behind

背后的代码

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 5; i++)
    {
        var button = new Button
        {
            ID = "Button" + i,
            CommandArgument = i.ToString(),
            Text = "Submit" + i
        };
        button.Command += Load_Items;
        PlaceHolder1.Controls.Add(button);
    }
}

private void Load_Items(object sender, CommandEventArgs e)
{
    int id = Convert.ToInt32(e.CommandArgument);
    // Do something with id
}

回答by Kai Hartmann

You need a container control on your page. Try an asp panel for example. Then in your codebehind you do panel.controls.add(btnSave); And don't forget to do it on every site load. http://support.microsoft.com/kb/317515/en-us

您的页面上需要一个容器控件。例如,尝试使用 asp 面板。然后在你的代码隐藏中你做 panel.controls.add(btnSave); 并且不要忘记在每个站点加载时都这样做。http://support.microsoft.com/kb/317515/en-us