c# - 单击多个文本框的事件

标签 c# winforms text textbox

所以我需要一种方法,当有人在 8x8 文本框网格中单击文本框时,他们单击的文本框中的文本会更改为某些内容。我的网格设置在一个名为 textboxes[,] 的变量中,因此如果您键入 textboxes[0,0],您将获得网格中的第一个框。截至目前,以我非常有限的知识,我有这个。

 for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {

                textboxes[i, j].Click += new EventHandler(textboxes_Click);

            }
        }

然后只要单击其中一个框,我就可以处理。如果你有更好的方法,我很想听听。我只是不知道如何访问被点击的框,主要是文本。希望我已经很好地解释了这一点。感谢所有的帮助!

-刘易斯

最佳答案

你的方法很好。你只需要在事件中定义一些额外的信息来处理它,如下:

我们可以定义一个类来存储文本框的位置:

public class GridIndex
{
    //stores the position of a textbox
    public int ipos { get; set; }
    public int jpos { get; set; }
}

您的代码经过轻微修改:

for (int i = 0; i < 8; i++)
  for (int j = 0; j < 8; j++)
  {
    textboxes[i, j].Click += new System.EventHandler(this.textBox_Click);
    textboxes[i, j].Tag = new GridIndex() { ipos = i, jpos = j };
  }

然后是你的处理程序:

    private void textBox_Click(object sender, EventArgs e)
    {
        TextBox textBox = sender as TextBox;

        if (textBox != null)
        {
            //Here your have the text of the clicked textbox
            string text = textBox.Text;
            //And here the X and Y position of the clicked textbox
            int ipos = (textBox.Tag as GridIndex).ipos;
            int jpos = (textBox.Tag as GridIndex).jpos;   
        }
    }

编辑:我对代码做了一些修改,请查看。

关于c# - 单击多个文本框的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4213328/

相关文章:

C# - 随机旋转多边形

C# .Net 3.5 解压缩 zip 文件没有第 3 方

mysql - varchar 与 mediumtext

c# - cshtml中 '@'标志是什么意思?

c# - 为什么 WhereSelectArrayIterator 不实现 ICollection?

.net - 使用 Firebase/Pusher/Pubnub 在 .Net 桌面应用程序和 Web 应用程序之间来回推送通知

html - 背景颜色不会覆盖文本 div

python-3.x - 如何在文本文件上编写控制台输出

c# - 根据特定属性维护排序顺序的集合类?

c# - 如何确保线程安全的 Web API 基础 Controller 方法