[英]Value increment of textbox in C#.net
我有2个文本框和1个按钮textbox1,textbox2和1个增量按钮。两个文本框初始化为1.如果我将单击textbox1然后单击incr按钮,值属于textbox1将仅增加。每当我点击textbox2再次点击incr按钮,textbox2值将增加。 我该怎么做?
您没有说您是在WinForms还是WPF中,所以我不会显示任何代码。
在您的班级中有一个TextBox activeTextBox
。 在每个文本框的GotFocus事件中,设置activeTextBox =此文本框。 在按钮中单击,将activeTextBox的文本转换为整数,加一,然后转换回字符串并将文本设置回原位。
编辑 :
activeTextBox
是您需要设置的字段,设计人员不会为您创建。 如果将textBox1
的GotFocus
事件设置为activeTextBox = textBox1
,对于textBox2
则类似,则activeTextBox
将始终具有“当前”文本框。 然后在按钮的单击事件中,您可以在activeTextBox
上执行任何操作。 您根本不需要从按钮单击处理程序访问textBox1
或textBox2
。
这可以使用javascript在客户端完成。 在textbox1的焦点上更新一个隐藏字段值。 对于textbox2同样。 然后点击按钮,基于隐藏的f
private int pickedbox = 0
[...]
private void textBox1_Enter(...)
{
pickedbox = 0;
}
private void textBox2_Enter(...)
{
pickedbox = 1;
}
private void button1_Click(...)
{
switch(pickedbox)
{
case 0:
textBox1.Text = int.Parse(textBox1.Text)++;
break;
case 1:
textBox2.Text = int.Parse(textBox2.Text)++;
break;
}
}
创建一个Windows窗体应用程序并将此代码粘贴到form1.cs上
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
TextBox textbox1 = new TextBox(), textbox2 = new TextBox();
Button button1 = new Button();
int FocusedTextBox = 0;
public Form1()
{
InitializeComponent();
this.Load += new System.EventHandler(this.Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
textbox1.Text = textbox2.Text = "1";
textbox1.Location = new Point(100, 100);
textbox2.Location = new Point(100, 140);
button1.Location = new Point(100, 180);
textbox1.Click += new EventHandler(textbox1_Click);
textbox2.Click += new EventHandler(textbox2_Click);
textbox1.ReadOnly = true;
textbox2.ReadOnly = true;
this.Controls.Add(textbox1);
this.Controls.Add(textbox2);
this.Controls.Add(button1);
}
void textbox2_Click(object sender, EventArgs e)
{
FocusedTextBox = 2;
}
void textbox1_Click(object sender, EventArgs e)
{
FocusedTextBox = 1;
}
void button1_Click(object sender, EventArgs e)
{
if (FocusedTextBox ==1)
textbox1.Text = (int.Parse(textbox1.Text) + 1).ToString();
else if (FocusedTextBox == 2)
textbox2.Text = (int.Parse(textbox2.Text) + 1).ToString();
}
}
}
如果(textBox1.Focused){textBox1.Text =(Convert.ToInt32(textBox1.Text)+1)+“”;
}
else if (textBox2.Focused)
{
textBox2.Text = (Convert.ToInt32(textBox2.Text) + 1) + "";
}
else if (textBox3.Focused)
{
textBox3.Text = (Convert.ToInt32(textBox3.Text) + 1) + "";
}
但是“.Focused”总是在假。 为什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.