c# How to reference a dynamically created component?
I have some code that create a few components on the click of a button. 开发者_如何学JAVASomething like this.
CheckBox chk = new CheckBox();
chk.Top = 50;
chk.Left = 50;
chk.Text = "Check Box Test";
chk.Name = "chkTest"
this.Controls.Add(chk);
So how do I use this component. For example I tried this but got and error saying the component didn't exist. I just want to get their values.
if(chkTest.Checked)
{
//Do this
}
Please help.
Thanks in adv.
Either create a member variable in your class called chkTest that you can use later, or retrieve it on the fly from the Controls collection when needed, like so:
CheckBox chkTest = (CheckBox)Controls["chkTest"];
if(chkTest.Checked) {
// ...
}
If you only care about the control when it is checked or unchecked, use an event.
chk.Checked += new RoutedEventHandler(CheckBox_Checked);
chk.Unchecked += new RoutedEventHandler(CheckBox_Checked);
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBox chkBox = sender as CheckBox;
if (chkBox.IsChecked.Value)
{
// Do this...
}
}
Make sure to unsubscribe from the event handlers when you are finished with them.
You're referencing chkTest but you created chk.
You could declare the Checkbox as a member variable of your page. Then you would be able to access it more easily.
Class MyPage { CheckBox chkTest;
// then in page load // chkTest = new CheckBox(); ...
}
if ((Controls.Items["chkTest"] as CheckBox).Checked)
{
// Do this
}
should work, but it's not pretty to look at. :)
You could declare it as a variable, then use it like you did:
CheckBox chkTest = Controls.Items["chkTest"] as Checkbox;
if (chkTest.Checked)
{
// Do this
}
Look on this handy page for ways to manipulate and access your Control's collection of items: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection_members.aspx
精彩评论