Reputation: 65
I've got a UserControl that has two textboxes in it. Users can add Multiple copies of these UserControls as needed. Each UserControl is added to the bottom of a Panel. How would I go about getting information from these UserControls.
This is the code to add the UserControl that I'm currently Using:
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);
}
And here's the code for the MailingReference Class:
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);
}
I've tried using
foreach (Control c in pnlMailingPanel.Controls)
{
if (c is MailingReference)
{
foreach (Control c2 in MailingReference.Controls)
{
//do work
}
}
}
to get the data from the textboxes, but MailingReference.Controls doesn't exist.
I'm not sure how to go about looping through each MailingReference UserControl and getting the Data from the two textboxes in each one. Any Tips?
Upvotes: 0
Views: 54
Reputation: 70652
As near as I can tell, the main thing you have wrong is that you are trying to access the instance property Controls
via the class name. You should have this instead:
foreach (Control c in pnlMailingPanel.Controls)
{
MailingReference mailingReference = c as MailingReference;
if (mailingReference != null)
{
foreach (Control c2 in mailingReference.Controls)
{
//do work
}
}
}
Upvotes: 4