简体   繁体   中英

Adding Button Control Dynamically and it Click event

I am generating html from a class in Business layer.Here is my Code and its inside a loop.

 html = html + "<tr><td>" + Convert.ToString(dr["RowNumber"]) + "</td>" +
                    "<td>" + Convert.ToString(dr["ReportName"]) + "</td>" +
                    "<td>" + Convert.ToString(dr["ReportJob"]) + "</td>" +



                    "<td>" + Convert.ToString(dr["RID"]) + "</td></tr>";  //need to a button or link button to call server side method

Is it possible to add buttons and its click event here.

I am not sure of your exact need here, but if I understand correctly you are creating a button or a series of buttons in html that need to have an event on the back end to execute code.

What I would do in this case is create a button click even on the back end that checks the text or the name of the calling button and executes the proper code based on your need:

protected void ButtonClick(object sender, EventArgs e)
{
  DoSomeCode(((System.Web.UI.WebControls.Button)sender).Text);
}

OR:

protected void ButtonClick(object sender, EventArgs e)
{
  Switch(((System.Web.UI.WebControls.Button)sender).Text)
 {
    Case "Button1":
    //Do something
    Case "Button2":
    //Do something else
    etc....
 }
}

When generating the button do something like you need to have a place holder in your html to hold the buttons, then in your code behind you just add them in a loop.:

List<Button> buttonList = new List<Button>();
    for (int i = 0; i < 2; i++)
    {
        Button test = new Button();
        test.Text = i.ToString();
        test.Click += new EventHandler(ButtonClick);

        placeholder.Controls.Add(test);
    }

YES YOU can add button dynamically but it should be html button and you must fire the button

by using scripts in your form

in your bussiness layer

<td><button onClirntclick='btClick2()'  id=' + Convert.ToString(dr["RID"]' text='submit') +'></button></td></tr>"; 

and in script

<script  type="text/javascript">
function btClick2()
  {
  return confirm('OnClientClick script: Press OK to continue.');
// do your work
  }
</script>

because it will take button as plain text so you must dynamically write the html button

hope this helps you

Of course, browser just takes the code lines and interprets them, so write down your JavaScript code that handles your button click, and add it to your HTML . Before doing that, I recommend trying it within your browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM