我试图从不同的文本框中添加不同的数字,一旦将值输入到每个文本框中,总和值将显示在显示总值的标签中。例如。 textbox1 + textbox 2要在label1中显示的值。在C#中。请问我该如何解决这个问题?感谢
答案 0 :(得分:2)
这是一个使用两个文本框的非常简单的方法。假设您已正确连接事件处理程序,这应该适合您。肯定有更优雅的方法,但这应该让你开始。
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
SumAndDisplay();
}
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
SumAndDisplay();
}
private void SumAndDisplay()
{
int a;
int b;
if (Int32.TryParse(textBox1.Text, out a) && Int32.TryParse(textBox2.Text, out b))
{
label1.Content = (a + b).ToString();
}
}
答案 1 :(得分:0)
你去..请检查。请注意,您还可以使用jQuery进行dom元素访问过程。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="WebTest.JavaScript" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function CalculateTotal() {
var total = 0;
for (var e = 0; e < form1.elements.length; e++) {
var el = form1.elements[e];
if (el.type == 'text') {
if (el.value != "")
total += parseInt(el.value);
}
}
document.getElementById("lb").innerText = "Total is: " + total;
}
function ValidChar(e, objSrc, validchars) {
var key, keychar;
key = window.event.keyCode;
if (key == null) return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
validchars = validchars.toLowerCase();
if (validchars.indexOf(keychar) != -1)
return true;
if (key == null || key == 0 || key == 8 || key == 9 || key == 13 || key == 27)
return true;
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:TextBox ID="txt01" runat="server" onfocusout="CalculateTotal();" onkeypress="return ValidChar(event,this,'0123456789')"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txt02" runat="server" onfocusout="CalculateTotal();" onkeypress="return ValidChar(event,this,'0123456789')"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txt03" runat="server" onfocusout="CalculateTotal();" onkeypress="return ValidChar(event,this,'0123456789')"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txt04" runat="server" onfocusout="CalculateTotal();" onkeypress="return ValidChar(event,this,'0123456789')"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lb" runat="server"></asp:Label>
</td>
</tr>
</table>
</form>
</body>
</html>