我遇到动态运行时控件的问题。
我为每个记录创建一组控件以显示在表单上。
我在每个控件上添加记录ID作为标记,以识别它们属于哪个记录。
While rCONT.Read
Dim txtphome As New TextBox
txtphome.Name = "phone" + rCONT.Item("pcontID").ToString
txtphome.Text = rCONT.Item("pcontPhHome").ToString
txtphome.Tag = rCONT.Item("pcontID").ToString
tcPatientDetails.TabPages(2).Controls.Add(txtphome)
AddHandler txtphome.LostFocus, AddressOf SaveContactChange
AddHandler txtphome.GotFocus, AddressOf SetContactNumber
End While
在SetContactNumber中我想保存标签值我如何识别触发它的控件
答案 0 :(得分:4)
假设您的SetContactNumber事件定义为:
<强> C#强>
private void SetContactNumber(object sender, EventArgs e)
{
//Stuff that happens when the SetContactNumber event is raised...
}
<强> VB 强>
Private sub SetContactNumber(sender As object, e As EventArgs)
//Stuff that happens when the SetContactNumber event is raised
End Sub
Sender 参数是引发事件的对象。因此,您只需要将其强制转换并将值附加到标记:
<强> C#强>
((textbox)sender).tag = "Whatever you wanted to put in here";
<强> VB 强>
CType(sender, textbox).tag = "Whatever you wanted to put in here"
tag属性采用 object 类型的值,因此分配的值可以是您喜欢的任何值:字符串,对象,类的实例等。当您'时,您有责任投射该对象重新将它拉出标签属性以使用它。
因此,当您将所有内容放在一起时,这将拉出引发事件的对象,将其转换为文本框并将您指定的值转储到tag属性中。
<强> C#强>
private void SetContactNumber(object sender, EventArgs e)
{
textbox thisTextbox = (textbox)sender;
thisTextbox.tag = "Whatever you wanted to put in here";
}
<强> VB 强>
Private Sub SetContactNumber(sender As Object, e As EventArgs)
Dim thisTextbox As TextBox = CType(sender, Textbox)
thisTextbox.tag = "Whatever you wanted to put in here"
End Sub