1
votes

I'm developing a C# ASP.NET application under VS2010. I want to generate a dynamic table by writing HTML text into a literal, including dynamically inserted buttons on my table. I know how to create dynamic ASP.NET controls, but I have a small problem with dynamic HTML controls. I've created an HTML button but I don't know how to give it a server-side click function.

Can I create dynamic ASP.NET controls and insert them in my literal? How can I get a dynamically created button to trigger a server-side event?

I've used OnServerClick property for defining my server side function but it has no effect, how can I use this value?

1
Where is the table data coming from? Consider redoing your table creation using the Repeater control, which will give you much more flexibility in generating your table (including having server-side buttons). - saluce
I know there are better ways of performing this action but I must use literal, I can create button this button tag but I don't know how to add a click event for it - Ali_dotNet

1 Answers

1
votes

If you want post back on your button click, you will have to add __doPostBack function on it's onclick event, for this you can add a button like

StringBuilder dynamicHtml = new StringBuilder();
dynamicHtml.Append("Your Html Code");
dynamicHtml.Append("<input type='button' id='btn1' name='btn1' onclick='__doPostBack(\'btn1\',\'\')' value='Click Here' />"); 

when you click on it, it will post back, and you can check Request.Form["__EVENTTARGET"] to find who post back the page.

By checking Request.Form["__EVENTTARGET"] in Page_Load event handler, you can call your any server side method like

protected void Page_Load(object sender, EventArgs e)
{
    var eventTarget = Request.Form["__EVENTTARGET"].ToString();

    if(eventTarget == "btn1")
    {
        CallMethod1();
    }
}


private void CallMethod1()
{
    //Code which you want to run
}