我認爲馬克和GraemeF的答案是偉大的,但我要回答(反正)添加爲微可供選擇的方法的一個例子。這種方法反映了我的「懶散路徑」:)編程哲學。注意這個例子需要Linq。
我的第一個目標是讓一個TextBox類型的變量可用來保存當前活動的TextBox(或者如果需要從以外訪問表單,我可以通過公共屬性訪問它) :如果我能得到它,那麼我可以通過簡單的方式訪問當前活動的TextBox的當前Text:只需使用.Text屬性(不需要轉換)。
//on the Form where the TextBoxes are : make into a Public Property
// if you need to access this from outside the Form holding the TextBoxes
// a Form-level variable
private TextBox theActiveTB;
然後,在表上,我會做窗體的Load事件建立文本框的集合,對我來說:並確保他們訂閱了相同的「按鍵響應和」輸入事件:
// on the Form where the TextBoxes are : a Form-level variable
private List<TextBox> tbList;
// build the list of TextBoxes and set the same 'Enter event for each of them
// note the assumption that every TextBox on the Form is going to be handled
// in exactly the same way : probably better to isolate them in a Panel in case
// you have other TextBoxes for other purposes ; then you'd just use the same
// code here to enumerate all the TextBoxes in the Panel
private void Form1_Load(object sender, EventArgs e)
{
tbList =
(
from TextBox theTB in this.Controls.OfType<TextBox>()
select theTB
).ToList();
foreach (TextBox theTB in tbList)
{
theTB.KeyPress +=new KeyPressEventHandler(theTB_KeyPress);
theTB.Enter +=new EventHandler(theTB_Enter);
}
}
// so here's what the Enter event might look like :
private void theTB_Enter(object sender, EventArgs e)
{
theActiveTB = (TextBox)sender;
// reality check ...
// Console.WriteLine("entering : " + theActiveTB.Name);
}
// so here's what the KeyPress event might look like :
private void theTB_KeyPress(object sender, KeyPressEventArgs e)
{
// do what you need to do here
// access the Text in the Textbox via 'theActiveTB
// reality check
// Console.WriteLine(theActiveTB.Name + " : " + e.KeyChar);
}
爲什麼還要製作List <TextBox>使用Linq?畢竟,你可以循環遍歷表單(或面板,或任何容器),並檢查每個控件的類型,然後,如果它是一個文本框,當場指派事件處理程序。我之所以選擇製作一個TextBoxes的通用列表,是因爲:當我有一個具有特殊共享標識,目的或行爲集合的集合時,通常情況下我會想要對其內容做其他事情作爲「組」或「組」。
只是爲了「具體化」我在上面提到的在通用列表中收集類似元素/類/控件的優點的陳述:假設我有一個包含所有20個文本框的列表:我想禁用它們all:tbList.ForEach(tb => {tb.Enabled = false;}); ......好好照顧它。最好的,比爾 –
BillW
2009-12-11 00:17:34