我想构建自定义控件,其中包含显示表格的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'也未被调用。
答案 0 :(得分:0)
宣布你的新活动:
public event EventHandler OnButton1Click;
public event EventHandler OnButton2Click;
public event EventHandler OnButton3Click;
这在每个按钮的click方法中执行以下操作:
public void Button1_Click(object sender, EventArgs e)
{
if (OnButton1Click != null)
OnButton1Click(this, null);
}
答案 1 :(得分:0)
在MyCustomControl
课程中,定义带有(object sender, EventArgs e)
并返回void
的事件。
然后添加(仍在MyCustomControl中)内部按钮的click
事件的事件处理程序。
在这些方法中,执行CustomClickEvent.Invoke()
。
然后,在包含自定义控件的页面中,执行myControl.CustomClickEvent += new CustomClickEvent(name_of_method_within_page);
答案 2 :(得分:0)
要从自定义控件渲染asp控件,请使用渲染基本方法:
protected override void Render(HtmlTextWriter writer)
使用此方法在控件之前准备
protected override void CreateChildControls()