我想构建由显示表格的 html 代码组成的自定义控件,并且在该表格的页脚中我需要添加三个按钮。我所做的是从 WebControl 类继承:
public class MyCustomControl : WebControl {
protected override void RenderContents(HtmlTextWriter output)
{
// using output.Write I write the table in html code
// and I write the three buttons using <input> tag in html not <asp:button> tag
}
}
我想要在这里为我编写的每个按钮添加三个事件,这些事件将在用户界面中使用并在单击正确的按钮时触发:
<asp:MyCustomControl runat="server" id="myCtrl" onButton1Click="Button1_Click" onButton2Click="Button2_Click" />
我怎样才能做到这一点 ?
谢谢
* *UPDATE1:
我的自定义控件中的渲染代码是这样的:
protected override void RenderContents(HtmlTextWriter output)
{
output.Write("<table> ......");
output.Write("<input id='button1' type='button'>");
output.Write("<input id='button2' type='button'>");
output.Write("<input id='button3' type='button'>");
output.Write(".........</table>");
}
那么我如何让'button1'在服务器端触发事件呢?
* *UPDATE2:
这是代码的样子:
public class MyCustomControl : WebControl
{
public Button Button1 = new Button {Text = "Button1"};
public Button Button2 = new Button {Text = "Button2"};
public event EventHandler Button1_Click;
public event EventHandler Button2_Click;
protected override void OnPreRender(EventArgs e)
{
Button1.Click += Button1Click;
Button2.Click += Button2Click;
base.OnPreRender(e);
}
protected override void RenderContents(HtmlTextWriter output)
{
using (var plh = new PlaceHolder())
{
var htmlCode = new StringBuilder();
htmlCode.Append("....html code for table...");
var container = new HtmlGenericControl { InnerHtml = htmlCode.ToString() };
plh.Controls.Add(container);
plh.Controls.Add(Button1);
plh.Controls.Add(Button2);
plh.RenderControl(output);
htmlCode.Append("..../html code for table...");
}
}
private void Button1Click(object sender, EventArgs e)
{
if (Button1_Click != null)
Button1_Click(this, e);
}
private void Button2Click(object sender, EventArgs e)
{
if (Button2_Click != null)
Button2_Click(this, e);
}
在 page.aspx 中:
<cc1:MyCustomControl ID="myCtrl" runat="server" onbutton1_click="MyCustomControl_Button1_Click" />
但即使这样,button1 的点击方法 'MyCustomControl_Button1_Click' 也没有被调用。