如何从在用户控件中创建的文本框中获取值
本文关键字:文本 获取 创建 用户 控件 | 更新日期: 2023-09-27 18:34:25
我有一个用户控件,里面有两个文本框。用户可以根据需要添加这些用户控件的多个副本。每个用户控件都添加到面板的底部。我将如何从这些用户控件中获取信息。
这是添加我当前正在使用的用户控件的代码:
private void btnAddMailing_Click(object sender, EventArgs e)
{
//Set the Panel back to 0,0 Before adding a control to avoid Huge WhiteSpace Gap
pnlMailingPanel.AutoScrollPosition = new Point(0,0);
/*I know this isn't the best way of keeping track of how many UserControls
I've added to the Panel, But it's what i'm working with right now.*/
int noOfMailings=0;
foreach (Control c in pnlMailingPanel.Controls)
{
if (c is MailingReference)
noOfMailings++;
}
//Add the New MailingReference to the bottom of the Panel
/*1 is the type of Mailing, noOfMailings Determines how many mailings we've sent for
this project*/
MailingReference mr = new MailingReference(1, noOfMailings);
mr.Location = new Point(MRXpos, MRYpos);
MRYpos += 120;
pnlMailingPanel.Controls.Add(mr);
}
下面是 MailingReference 类的代码:
public partial class MailingReference : UserControl
{
public String Date
{
get { return txtDate.Text; }
set { txtDate.Text = value; }
}
public String NumberSent
{
get { return txtNoSent.Text; }
set { txtNoSent.Text = value; }
}
/// <summary>
/// Creates a Panel for a Mailing
/// </summary>
/// <param name="_letterType">Type of 0 Letter, 1 Initial, 2 Final, 3 Legal, 4 Court</param>
public MailingReference(int _letterType, int _mailingNo)
{
InitializeComponent();
//alternate colors
if (_mailingNo % 2 == 0)
panel1.BackColor = Color.White;
else
panel1.BackColor = Color.LightGray;
switch (_letterType)
{
case 1:
lblLetter.Text = "Initial";
break;
case 2:
lblLetter.Text = "Final";
break;
case 3:
lblLetter.Text = "Legal";
break;
case 4:
lblLetter.Text = "Court";
break;
default:
break;
}
lblMailingNumber.Text = _mailingNo.ToString();
}
private void label1_Click(object sender, EventArgs e)
{
this.Parent.Controls.Remove(this);
}
我试过使用
foreach (Control c in pnlMailingPanel.Controls)
{
if (c is MailingReference)
{
foreach (Control c2 in MailingReference.Controls)
{
//do work
}
}
}
以从文本框中获取数据,但 MailingReference.Controls 不存在。
我不确定如何遍历每个邮件引用用户控件并从每个文本框中获取数据。有什么提示吗?
据
我所知,您错误的主要事情是您尝试通过类名访问实例属性Controls
。你应该有这个:
foreach (Control c in pnlMailingPanel.Controls)
{
MailingReference mailingReference = c as MailingReference;
if (mailingReference != null)
{
foreach (Control c2 in mailingReference.Controls)
{
//do work
}
}
}