我已经使用扩展类实现了可点击的表单元格。但是,当我在主类中调用事件处理程序/onclick方法时,事件处理程序不起作用。
扩展的可点击表格单元格类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Member
{
public class TableCellClick: TableCell, IPostBackEventHandler, INamingContainer
{
private static readonly object click_event = new object();
// public handles for adding and removing functions to be called on the click event
public event EventHandler Click
{
add
{
Events.AddHandler(click_event, value);
}
remove
{
Events.RemoveHandler(click_event, value);
}
}
// define parent function that will be called when the container is clicked
protected void OnClick(EventArgs e)
{
EventHandler h = Events[click_event] as EventHandler;
if (h != null)
{
h(this, e);
}
}
// specify the "post back event reference" or id of the click event
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
writer.AddAttribute(HtmlTextWriterAttribute.Onclick,
Page.ClientScript.GetPostBackEventReference(this, "custom_click"));
}
// link the custom click id to the click function
void System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
if(eventArgument == "custom_click")
{
OnClick(EventArgs.Empty);
}
}
}
}
我的主类中的方法:
memPanel.Visible = true;
//Set a table width.
memTable.Width = Unit.Percentage(40.00);
//Create a new row for adding a table heading.
TableRow tableHeading = new TableRow();
//Create and add the cells that contain the msno column heading text.
TableHeaderCell msnoHeading = new TableHeaderCell();
msnoHeading.Text = "M'Ship No.";
msnoHeading.HorizontalAlign = HorizontalAlign.Left;
tableHeading.Cells.Add(msnoHeading);
//Create and add the cells that contain the Name column heading text.
TableHeaderCell nameHeading = new TableHeaderCell();
nameHeading.Text = "Name";
nameHeading.HorizontalAlign = HorizontalAlign.Left;
tableHeading.Cells.Add(nameHeading);
memTable.Rows.Add(tableHeading);
while (reader.Read())
{
TableRow detailsRow = new TableRow();
TableCellClick msnoCell = new TableCellClick();
msnoCell.Text = reader["MSNo"].ToString();
msnoCell.Click += cellClick;
detailsRow.Cells.Add(msnoCell);
TableCellClick nameCell = new TableCellClick();
nameCell.Text = reader["fName"].ToString();
nameCell.Click += cellClick;
memTable.Rows.Add(detailsRow);
}
onclick方法:
protected void cellClick(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("cell click");
memPanel.Visible = false;
basicInfo.Visible = true;
}
有人知道哪里出了问题吗?
请尝试以下操作::
msnoCell.Click += new System.EventHandler(cellClick);
之所以没有调用它,是因为每次单击按钮时都有回发方法
我的单元格不是在pageload方法中创建的,这就是为什么在单击单元格按钮时没有调用它的原因。