![](/img/trans.png)
[英]How can I dynamically fire an event for a textbox which is dynamically created?
[英]How to 'select' correct Textbox out of List<Textbox> which are created dynamically?
在一个学校项目中,我必须在MouseClick事件中创建“动态”(如果正确的话)文本框。通过单击最近创建的文本框,将打开另一个窗体(由另一个MouseClick事件)。
在该新表单中,我想将文本从最近创建的文本框中更改为我在新文本框中插入的文本。
我的问题是,当我创建多个文本框时,不会更新正确的文本框,它总是编辑我创建的最后一个文本框。
private int tbcount = 1;
//Dynamische textbox
private TextBox tbNewUseCase;
private List<TextBox> textboxlist = new List<TextBox>();
public frm_use_case()
{
InitializeComponent();
}
//Textbox clicks
private void tbNewUseCase_MouseClick(object sender, MouseEventArgs e)
{
ucform usecase = new ucform(this, tbNewUseCase);
usecase.Show();
}
//Update textbox text
public void UpdateTbTekst(TextBox tb, string tekst)
{
tb.Text = tekst;
}
//Mouseclick on the form
private void frm_use_case_MouseClick(object sender, MouseEventArgs e)
{
if (rbTekst.Checked)
{
//Only in a certain area I want a textbox to be created
if (e.X > 288 && e.X < 451 - 100 && e.Y > 66 && e.Y < 421)
{
tbNewUseCase = new TextBox();
tbNewUseCase.Name = "tbUseCase" + tbcount;
tbNewUseCase.Location = new Point(e.X, e.Y);
tbNewUseCase.ReadOnly = true;
tbNewUseCase.MouseClick += tbNewUseCase_MouseClick;
this.Controls.Add(tbNewUseCase);
textboxlist.Add(tbNewUseCase);
tbcount++;
}
}
}
这是单击文本框之一时创建的另一种形式的代码。
private frm_use_case mnform;
private TextBox currentusecase;
public TextBox Currentusecase
{
get
{
return currentusecase;
}
set
{
currentusecase = value;
}
}
public ucform(frm_use_case mainform, TextBox usecase)
{
InitializeComponent();
mnform = mainform;
Currentusecase = usecase;
}
//Calls the method that changes the text in the main form
//tbNaam is a textbox.
private void tbNaam_TextChanged(object sender, EventArgs e)
{
mnform.UpdateTbTekst(huidigeusecase, tbNaam.Text);
}
编辑:我的问题已由史蒂夫成功回答!
您将在第一个窗体MouseClick事件中创建TextBoxes列表。
在该代码中,您使用一个TextBox的新实例反复初始化一个名为tbNewUseCase
的TextBox引用。 在循环的最后,引用变量tbNewUseCase
引用了最后创建的文本框。
现在,当您将此引用传递给第二种形式时,更新将在该实例上发生,动态创建并添加到列表的其他实例完全不受影响。 因此,您只能更改一个文本框。
现在,如果您希望更改在单击的文本框上发生,那么您应该更改传递文本框以将其更新为ucform
//Textbox clicks
private void tbNewUseCase_MouseClick(object sender, MouseEventArgs e)
{
// Here sender is a reference to the currently clicked textbox
// and you could pass that reference to the ucform constructor
ucform usecase = new ucform(this, sender as TextBox);
usecase.Show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.