[英]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.