日期:2014-05-17  浏览次数:20378 次

asp.NET 怎样给TextBox添加onkeyup事件并用来调用类(.cs)中方法---在线跪求,回帖以分相谢
页面
test.aspx
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="runTimeTxB" runat="server"></asp:TextBox>
    <asp:TextBox ID="shutDownTimeTxB" runat="server"></asp:TextBox>
    <!--根据前面2个TextBox框输入的值,自动计算停机率并赋值第三个TextBox-->
    <asp:TextBox ID="shutdownRateTxB" runat="server" ></asp:TextBox>  
    </form>
</body>
类文件
test.cs
         //加载页面
 protected void Page_Load(object sender, EventArgs e)
        {
            runTimeTxB.Attributes.Add("onkeyup", "calcShutdownRate();");
            runTimeTxB.Attributes["onkeyup"] = "calcShutdownRate();";
            
        }
        //计算停机率
        private void calcShutdownRate()
        {
                Double x = Convert.ToDouble(runTimeTxB.Text == "" ? "0" : runTimeTxB.Text);
                Double y = Convert.ToDouble(shutDownTimeTxB.Text == "" ? "0" : shutDownTimeTxB.Text);
                Double result = 0;
                if (x != 0 && y != 0)
                    result = Math.Round(y / (x + y) * 100, 2);
                shutdownRateTxB.Text = result.ToString();
        }

我需要在页面前台实现TextBox间联动赋值,但是不想用JS,要通过onkeyup来调用类文件.cs中某函数,本来OnTextChanged可以实现,但是OnTextChanged反应不灵敏(需失去焦点才触发)。
所以请问该怎么实现?以上代码执行总报错——calcShutdownRate()未定义
请高手附可执行的详细代码,谢谢

------解决方案--------------------
<form id="form1" runat="server">
        <div>
            <asp:LinkButton ID="LinkButton1" Text="" runat="server" />
            <asp:TextBox ID="shutdownRateTxB" runat="server" onkeyup='javascript:__doPostBack("shutdownRateTxB", "");'  OnTextChanged="shutdownRateTxB_TextChanged1"></asp:TextBox>            
        </div>
    </form>
     
public partial class _Default : System.Web.UI.Page
{