如何在各种文本框中添加数字以及在标签中显示的总和
本文关键字:标签 显示 添加 文本 数字 | 更新日期: 2023-09-27 18:22:06
Am试图从不同的文本框中添加不同的数字,这样,一旦将值输入到每个文本框中,合计值就会显示在显示总值的标签中。例如,要在标签1中显示的文本框1+文本框2的值。在C#中。请问我该怎么办?感谢
这里有一个使用两个文本框的非常简单的方法。假设您正确地连接了事件处理程序,这应该对您有效。当然还有更优雅的方法,但这应该让你开始。
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();
}
}
给你。。请检查。请注意,您也可以使用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>