[英]Button handler event not firing with dynamically created buttons
我正在根據數據庫值動態創建按鈕,這是生成按鈕的代碼。
test.GetSubjects();
int subjectid = 0;
// Current row count.
int rowCtr;// = 0;
// Total number of cells per row (columns).
int cellCtr;
// Current cell counter.
int cellCnt;
//count number of rows in dataset
int rN = test.dsSubjects.Tables[0].Rows.Count;
cellCnt = 4;
for (rowCtr = 1; rowCtr <= rN; rowCtr++)
{
// Create a new row and add it to the table.
TableRow tRow = new TableRow();
Table1.Rows.Add(tRow);
for (cellCtr = 1; cellCtr <= 4; cellCtr++)
{
//
Button button = new Button();
//
HyperLink link = new HyperLink();
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
button.Click += ButtonClick;
/* If the rowcounter is equal to the record numbers
* then it has to break because if not it will throw an error
* saying that there is no row at ending position */
if (rowCtr == rN)
break;
string myStr = test.dsSubjects.Tables[0].Rows[rowCtr - 1]["SubjectName"].ToString();
int myID = Convert.ToInt32(test.dsSubjects.Tables[0].Rows[rowCtr - 1]["SubjectID"].ToString());
button.ID = Convert.ToString(myID);
button.Text = myStr;
//button.PostBackUrl = "~/WebForm2.aspx?SubjectID=" + myID;
button.CssClass = "DynamicButtonOverlay";
button.OnClientClick = " return ShowModalPopup()";
tCell.Controls.Add(button);
tCell.CssClass = "DynamicButtonOverlay";
tRow.Cells.Add(tCell);
rowCtr++;
/* If the cellcount is 3 then it needs to break, if not then
* you'll miss every 4rth record, don't know why. But this works */
if (cellCtr == 4)
{
rowCtr = rowCtr - 1;
break;
}
}
}
此代碼可以正常工作。 正如您在代碼中看到的那樣,它應該具有稱為處理程序事件的按鈕,但永遠不會調用處理程序。 現在,當創建按鈕並單擊按鈕時,它正在調用javascript函數以顯示ajaxmodalpopup,這是javascript代碼
<script type="text/javascript">
function ShowModalPopup() {
$find("mpe").show();
return false;
}
function HideModalPopup() {
$find("mpe").hide();
return false;
}
我制作的事件處理程序是這樣的。
private void ButtonClick(object sender, EventArgs e)
{
Button button = (Button)sender;
Label1.Text = "howdy";
}
這個處理程序用於測試,這就是為什么我讓它看起來像它那樣。
我在處理程序上設置了一個斷點,但是當我單擊一個按鈕時,它根本沒有調用處理程序,我也不知道為什么。 我需要這些按鈕中的任何一個來運行事件,因為調用modalpopup時,我將把按鈕id(這是數據庫中的id)傳遞給modalpopup,它將有一個用於編輯subject(button)數據庫的形式值,然后更新數據庫,然后在更新后,我將使用modalpopup重定向來回發頁面以刷新。
所以有兩個問題:按鈕沒有調用處理程序,如果我可以使它工作,那么我需要獲取被調用按鈕的ID,以便可以填充modalpopup中的字段。
按鈕的生成是在pageload事件上完成的。
根據添加控件的時間,您將必須在Page Init或OnLoad的每次回發中重新創建控件。
這是最好的解釋之一 。
我發現了導致此問題的原因,這是JavaScript函數。
<script type="text/javascript">
function ShowModalPopup() {
$find("mpe").show();
return false;
}
function HideModalPopup() {
$find("mpe").hide();
return false;
}
出於某種原因(我不知道),它不允許調用事件處理程序。 刪除JavaScript后,按鈕便可以調用事件處理程序。 可能與使按鈕在OnclientClick上調用JavaScript函數以及使按鈕還調用事件處理程序有關。 我不知道。 但現在可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.