[英]Click Event for multiple Textboxes
所以我需要一種方法,當一個人點擊8x8文本框網格中的文本框時,他們點擊的文本框中的文本將更改為某些內容。 我的網格設置在一個名為textboxes[,]
的變量中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);
}
}
然后,只要單擊其中一個框,我就可以處理。 如果你有更好的方法,我很樂意聽到它。我只是不知道如何訪問被點擊的框,主要是文本。 希望我已經解釋得這么好了。 感謝您的幫助!
-Lewis
你的方法很好。 您只需定義一些其他信息即可在事件中處理它,如下所示:
我們可以定義一個類來存儲文本框位置:
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;
}
}
編輯 :我對代碼做了一些更改,請查看。
您的EventHandler有一個名為sender的對象作為參數。 您必須將其強制轉換為TextBox,然后才能獲取文本框的文本。
您的事件處理程序具有簽名:
void Handler(object sender, EventArgs args)
sender是對單擊的TextBox的引用。 如果此時你還需要知道i * j我創建了一個派生自TextBox
的類,該類具有存儲在其中的那些數字。
您可以通過編寫以下代碼來獲取文本框值
TextBox txt =(TextBox)sender; string text = txt.Text.ToString(); MessageBox.show(文本);
希望這對你充滿幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.