[英]How to access the Items of a User Control
I have a C# Form that prints multiple instances of a User Control . 我有一个C#表单打印用户控件的多个实例。 Let's say that the form prints 5 instances of the User Control (Please see the link attached). 假设表单打印了5个用户控件实例(请参阅附件中的链接)。 How can I store/save the data inputted in all User Controls? 如何存储/保存所有用户控件中输入的数据? Thanks 谢谢
Here is the screenshot of the C# Form: 以下是C#表单的屏幕截图:
You'll have to store the User Controls when you instantiate them in a List or something. 在List或其他东西中实例化它们时,您必须存储用户控件。
You could have a class like this: 你可以有这样一个类:
class SomeUC : UserControl
{
public SomeUC()
{
}
// A public method.
public string GetData()
{
return textBox1.Text;
}
}
Where textBox1
is the Name of a TextBox
in your SomeUC
其中textBox1
是SomeUC
TextBox
的名称
And then inside your main or something. 然后在你的主要或其他内部。
// Instantiate a List that will hold your UserControls, this has to be outside all methods
List<SomeUC> list = new List<SomeUC>();
// And now when you want to build your UCs
// Instantiate your UserControl
SomeUC uc1 = new SomeUC();
// Store your UserControl in a List or something (Can't help you with that)
list.Add(uc1);
Add as much as you want. 添加尽可能多的内容。 A List
is not the only way you can do that, but since you don't know how many UserControls you're going to build beforehand, it makes since to use a List
. List
不是你能做到的唯一方法,但由于你不知道你将要预先构建多少个UserControl,因此它会使用List
。 And then you can access them from the list by their index. 然后您可以通过索引从列表中访问它们。
SomeUC uc1 = list[0];
string data = uc1.GetData();
This is an example of accessing one control (the TextBox
) in your SomeUC
. 这是访问SomeUC
一个控件( TextBox
)的SomeUC
。 For other classes (such as the ComboBox
) the interaction is different. 对于其他类(例如ComboBox
),交互是不同的。 Meaning you won't have a Text
property in the ComboBox
. 这意味着ComboBox
没有Text
属性。 You'll have to figure out things like that on youself. 你必须在自己身上找出类似的东西。 A little research is what it takes. 需要进行一些研究。 You can always come back if you couldn't find a solution for something. 如果找不到某种解决方案,您可以随时回来。
尝试使用此代码访问页面中的用户控件
Dim txtName As TextBox = TryCast(UserControlName.FindControl("txtName"), TextBox)
You can create a property like this for each item in user control. 您可以为用户控件中的每个项创建这样的属性。
public string DG
{
get
{
return txtDG.Text;
}
set
{
txtDG.Text = value;
}
}
Then you can access the control value by using following line in your form. 然后,您可以使用表单中的以下行访问控件值。 supposed you have created a usercontrol MyControl and you have placed some object of this control in FlowLayoutPenal (pnlFLP). 假设您已经创建了一个usercontrol MyControl,并且您已在FlowLayoutPenal(pnlFLP)中放置了此控件的一些对象。
To get value from control 从控制中获取价值
string DG = ((MyControl)pnlFLP.Controls[0]).DG;
To set value in control 在控件中设置值
((MyControl)pnlFLP.Controls[0]).DG = "1";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.