簡體   English   中英

鏈接動態創建的文本框和標簽

[英]Linking dynamically created text boxes and labels

我創建了一個TextBoxes數組和一個Labels數組。 當信息在文本框中更新時,我希望它更改標簽。 我將如何做到這一點? 下面是我的代碼。 我還沒有創建我認為是我需要幫助的部分的EvenHandler。 全部使用Windows應用程序形式的C#。

textBoxes = new TextBox[value];
labels = new Label[value];

for (int i = 1; i < value; i++)
{
    textBoxes[i] = new TextBox();
    textBoxes[i].Location = new Point(30, ToBox.Bottom + (i * 43));

    labels[i] = new Label(); 
    labels[i].Location = new Point(TopBox3[i].Width + 140, TopBox3[i].Top +3);

    textboxes[i].ValueChanged += new EventHandler(this.TextBox_ValueChanged) ;

    this.Controls.Add(labels[i]);
    this.Controls.Add(textBoxes[i]);
}

您可以記住Tag屬性中TextBox的索引

 textBoxes[i].Tag = i;

然后在事件處理程序中使用此值來獲取相應的標簽(假設您將labels數組作為局部變量保存)

protected void TextBox_ValueChanged(object sender, EventArgs e)
{
  TextBox textbox = sender as TextBox;
  if(textbox==null)
    return;
  int index = Convert.ToInt32(textbox.Tag);
  if(index >= 0 && index < this.labels.Length)
  {
    Label label = this.labels[index];
    /* ... */
  }
}

您應該這樣寫:

    private void textBox1_ValueChanged(object sender, EventArgs e)
    {
        TextBox changedTxt = sender as TextBox;
        for (int i = 1; i < value; i++)
            if (textBoxes[i] == changedTxt)
            {
                Label lblToChange = labeld[i];
                lblToChange.Text = changedTxt.Text;
                break;
            }
    }

在該方法中,文本已更改的TextBox作為“發送者”傳遞。 您需要為它查看數組,因此可以識別索引“ i”,該索引可用於訪問相應的Label並設置其文本。

如蒂姆所說,順便說一句,事件是TextChanged,而不是ValueChanged。 此外,請注意,文本中的每次更改都會觸發該事件,即,一旦您按下一個鍵,標簽就會被更新。 如果您只想在用戶輸入完文本后才更新標簽,則應使用“離開”事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM