开发者

Click Event for multiple Textboxes

开发者 https://www.devze.com 2023-01-25 12:17 出处:网络
So I need a way for when a person clicks on a textbox inan 8x8 grid of textboxes, the text in the textbox they have clicked on is changed to something. My grid is set up in a variable called textboxes

So I need a way for when a person clicks on a textbox inan 8x8 grid of textboxes, the text in the textbox they have clicked on is changed to something. My grid is set up in a variable called textboxes[,] so if you type textboxes[0,0] you get the first box in the grid. As of now, with my very limited knowledge, I have this.

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

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

            }
        }

Then I can handle whenever one of the boxes is clicked. If you have a better way of doing this, I would love to hear it.I just dont know how to acces开发者_运维问答s the box that was clicked, mainly the text. Hope I have explained this well enough. Thanks for all the help!

-Lewis


Your approach is good. You only have to define some additional information to handle it in the event, as follows:

We can define a class to store the textbox position:

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

Your piece of code sightly modified:

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 };
  }

And then your handler:

    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;   
        }
    }

Edit: I did some changes to the code, please, review.


Your EventHandler has an object called sender as parameter. You have to cast it to an TextBox, then you can get the text of the textbox.


Your event handler has the signature:

void Handler(object sender, EventArgs args)

Where sender is a reference to the TextBox that was clicked. If you also need to know i * j at this point I'd created a class that derives from TextBox which has those numbers stored within it.


You can get the text box values by writting the following code

TextBox txt= (TextBox)sender; string text = txt.Text.ToString(); MessageBox.show(text);

Hope this will be help full for u

0

精彩评论

暂无评论...
验证码 换一张
取 消