问题
I am dynamically adding a RadioButtonList in the Code Behind. I want it so that the 'OnClick' does not call JavaScript, but instead it calls a method in my code behind.
Is this possible?
In addition, is there a way to set it up so that this say control has runat="server"?
回答1:
Yes, it is possible. Also, there is no need to have runat="server" since your are creating the control in code.
You need to set your RadioButtonList object's OnSelectedIndexChanged event. As @Robert mentioned, if you are creating controls dynamically you need to wrap them in the Page_Init().
protected void Page_Init(Object sender, EventArgs e) {
RadioButtonList radiobuttonlist = new RadioButtonList();
radiobuttonlist.SelectedIndexChanged += radiobuttonList_CheckedChanged;
//Set the AutoPostBack to true proptery to that the user action
// will immediately post-back to the server
radiobuttonlist.AutoPostBack = true;
}
private void radiobuttonList_CheckedChanged(object sender, EventArgs e) {
//Code you want to execut when a user selects a different item
}
Reference: https://msdn.microsoft.com/en-us/library/System.Web.UI.WebControls.ListControl.SelectedIndexChanged(v=VS.110).aspx
回答2:
You can use the Button Click Event https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.click(v=vs.110).aspx
回答3:
Be sure to add the control in the Page_Init()
portion of the code, not in Page_Load()
or later. Set up the event handler +=
line inside the Page_Init()
setup. The control should run server side if you do this. I'm not sure if runat="server"
will be explicitly set but the control will behave that way.
来源:https://stackoverflow.com/questions/32510291/set-the-onclick-to-call-a-client-method-when-dynamically-adding-control-in-cod