【发布时间】:2011-05-16 16:14:11
【问题描述】:
我有 2 个文本框和 1 个按钮 textbox1、textbox2 和 1 个增量按钮。两个文本框都由 1 初始化。如果我单击 textbox1 然后单击 incr 按钮,则属于 textbox1 的值只会增加。每当我将单击 textbox2 并再次单击 incr 按钮,只有 textbox2 的值会增加。 我将如何做到这一点?
【问题讨论】:
我有 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
【讨论】:
创建一个 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();
}
}
}
【讨论】:
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;
}
}
【讨论】:
if (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”总是返回 False。 为什么?
【讨论】: