栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在动态创建的ASP.net控件中动态创建ASP.net控件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在动态创建的ASP.net控件中动态创建ASP.net控件

这是向页面连续添加按钮的示例。每个新创建的按钮也可以向页面添加另一个按钮。可以与所有类型的控件一起使用。另外,您还必须在每个PostBack上重新创建动态控件,否则它们及其内容将丢失。

protected void Page_Load(object sender, EventArgs e){    //set the initial number of buttons    int buttonCount = 1;    //check if the viewstate with the buttoncount already exists (= postback)    if (ViewState["buttonCount"] != null)    {        //convert the viewstate back to an integer        buttonCount = Convert.ToInt32(ViewState["buttonCount"]);    }    else    {        ViewState["buttonCount"] = buttonCount;    }    //create the required number of buttons    for (int i = 1; i <= buttonCount; i++)    {        createButton(i);    }}private void createButton(int cnt){    //create a new button control    Button button = new Button();    button.Text = "Add another Button (" + cnt + ")";    //add the correct method to the button    button.Click += DynamicButton_Click;    //another control, in this case a literal    Literal literal = new Literal();    literal.Text = "<br>";    //add the button and literal to the placeholder    PlaceHolder1.Controls.Add(button);    PlaceHolder1.Controls.Add(literal);}protected void DynamicButton_Click(object sender, EventArgs e){    //get the current number of buttons    int buttonCount = Convert.ToInt32(ViewState["buttonCount"]) + 1;    //create another button    createButton(buttonCount);    //set the new button count into the viewstate    ViewState["buttonCount"] = buttonCount;}

更新

您还可以将a委托

Command
给按钮而不是委托给按钮
Click
,并以此将变量和按钮一起发送为
CommandArgument
。您将不得不稍微更改按钮的创建。

//add the correct method to the buttonbutton.Command += DynamicButton_Command;//now you can also add an argument to the buttonbutton.CommandArgument = "Create Hazard";

您还需要其他方法来处理按钮单击。

protected void DynamicButton_Command(object sender, CommandEventArgs e){    //get the current number of buttons    int buttonCount = Convert.ToInt32(ViewState["buttonCount"]) + 1;    //create another button    createButton(buttonCount);    //set the new button count into the viewstate    ViewState["buttonCount"] = buttonCount;    //get the commandargument from the button    string buttonArgument = e.CommandArgument.ToString();}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576318.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号