[英]How do I click a button in a list of the same named buttons in Selenium using C#
[英]How do I create buttons dynamically in C# onClick of another button? And then have those buttons also do the same
我试图制作一个C#网页,该网页根据表单提交的内容动态创建按钮,但是我一直走不通。 问题是(显然吗?)您只能在Page_Load期间挂接EventHandler,而不能在按钮的Click事件内挂接吗?
基本上我有一些代码来创建按钮:
private Button CreateButton(string id, string text) {
Button b = new Button();
b.ID = id;
b.Text = text;
b.Command += new CommandEventHandler(Button_Command);
b.CommandArgument = text;
return b;
}
当单击这些新按钮时,它们应该传递命令参数,并根据这些命令参数创建新按钮
void Button_Command(object sender, CommandEventArgs e) {
//Put code here that creates new buttons based on what's submitted
DoThis(e.CommandArgument.ToString());
}
但是,当我在按钮的Click事件中运行此代码时,不会为新创建的按钮挂接EventHandler。
第一次访问该页面时,只有一个文本输入和一个GO按钮。 它应该创建一堆新按钮及其命令参数:
protected void bntGo_Click(object sender, e EventArgs){
DoThis(txtInput.Text);
}
private void DoThis(string arg){
//Do some logic to create a Dictionary<string, int> object (sortedDict)
//based on the arg passed, then for each KeyValuePair in the Dictionary,
//add a button to a panel on the page, setting each button's commandarguments
//to each string in the dictionary
int count=1;
foreach (KeyValuePair<string, int> pair in sortedDict) {
pnlButtonsPanel.Controls.Add(CreateButton("Btn"+count.ToString(), pair.Key));
}
}
我该如何完成? 我不能每次页面加载时都运行DoThis()函数,因为DoThis()需要从其单击的按钮传递CommandArguments,而在page_load中则无法使用。
我究竟做错了什么? 我需要一种新方法。 我在这里盘算自己。
谢谢!
您无法注册处理程序,必须实际提交表单并解析服务器上命令的等效字符串。 因此,RunAt Server。 呈现的页面和服务器之间没有魔术连接,称为Javascript。
您是否遵循了这里的设计模式?
http://msdn.microsoft.com/zh-CN/library/system.web.ui.webcontrols.commandeventhandler.aspx
<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>
...
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
switch(e.CommandName)
{
case "Sort":
// Call the method to sort the list.
Sort_List((String)e.CommandArgument);
break;
您需要在Page_Init或Page_Load中添加事件处理程序的原因如下:
每次回发到服务器都会导致页面从头开始重建(除非它是一个完全静态的页面并且正在被缓存)。 这将导致所有动态更改(添加按钮,...)丢失。 因此,当您单击动态创建的按钮时,出于所有意图和目的,不要重新创建按钮以及Page_Init或Page_Load中的所有处理程序,则该按钮不存在于服务器端。
如果您需要保存包含每个按钮的详细信息的列表,只需使用ViewState
protected void Page_Init (object sender, EventArgs e)
{
//do your stuff
var buttonStuff = ViewState["MySaveButtonStuff"] as List<string>;
if (buttonStuff != null)
{
//create button method(s)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.