简体   繁体   English

当checkbox.checked值设置为true时强制回发帖子

[英]Force a post back when checkbox.checked value is set to true

I have a method that changes the checked attribute of a checkbox like this 我有一个方法可以更改像这样的复选框的checked属性

checkbox1.checked = true;

and then I have the eventhandler method : 然后我有eventhandler方法

checkbox1_checkedChanged(object obj, EventArgs args)

However, when I perform the changing of checked attribute to true, the event handler does not fire up. 但是,当我执行将checked属性更改为true时,事件处理程序不会启动。

How can I achieve this? 我怎样才能做到这一点?

I suspect that your function that does checkbox1.checked = true; 我怀疑你的函数是checkbox1.checked = true; is running server side, so could never cause a postback. 正在运行服务器端,因此永远不会导致回发。

If this is the case, and you just wish to invoke the code in your checked changed handler, you could just call the function directly, or refactor the code out into a common function. 如果是这种情况,并且您只想调用已检查更改的处理程序中的代码,则可以直接调用该函数,或将代码重构为常用函数。

您需要在元素上将AutoPostBack设置为true

<asp:CheckBox id="checkbox" runat="server" AutoPostBack="true" />

What you need to do is simply call the method handler you want fired because you're already server-side and so no event is going to fire because of a property value change. 您需要做的只是调用您想要触发的方法处理程序,因为您已经是服务器端,因此不会因为属性值更改而触发事件。 So, try this after setting checked to true: 因此,在将checked设置为true后尝试此操作:

checkbox1_checkedChanged(checkbox1, new EventArgs());

Well, you talk about "post back" so I assume you are creating a web page. 好吧,你谈到“回发”,所以我假设你正在创建一个网页。

The AutoPostBack property only indicates that the post back event will fire when the control's property is changed through the control itself on the web page since the event handler is bound to the control only. AutoPostBack属性仅指示当通过网页上的控件本身更改控件的属性时将触发回发事件,因为事件处理程序仅绑定到控件。

So, changing the control's property dynamically (with code on the server side) will never trigger the event handler. 因此,动态更改控件的属性(使用服务器端的代码)将永远不会触发事件处理程序。 Instead, you could just call the handler right after the change (like what Justin Harvey said). 相反,你可以在改变之后立即调用处理程序(就像Justin Harvey所说的那样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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