Using a control created on Form_Load in another event
I have two controls created on Form_Load
, a button and a combobox. I also have an event for the button, but the event should be able to see the newly created combobox.
When I try to call the combobox by it's name it says that it doesn't exist in this context.
private void Form1_Load(object sender, EventArgs e)
{
Button przycisk = new Button();
przycisk.Name = "przycisk";
przycisk.Dock = DockStyle.Bottom;
przycisk.Text = "Wybierz";
ComboBox kombo = new ComboBox();
kombo.Name = "kombo";
kombo.Dock = DockSt开发者_开发知识库yle.Bottom;
kombo.Items.Add("Przycisk");
kombo.Items.Add("Etykeita");
kombo.Items.Add("Pole tekstowe");
Controls.Add(kombo);
Controls.Add(przycisk);
przycisk.Click += new EventHandler(przycisk_Click);
}
private void przycisk_Click(object sender, EventArgs e)
{
kombo.Items.Add("Panel"); //just an example
}
Is there a way to make this work?
Only controls which are in used in markup with runat="server" will be class variables on your page. They are actually defined in the designer file.
What you'll want to do is in the class add something like the following where you have a class variable, then assign kombo in your page-load function. Then, it will exist in your click event handler.
// kombo is now scoped for use throughout this class
ComboBox kombo = null;
private void Form1_Load(object sender, EventArgs e)
{
Button przycisk = new Button();
przycisk.Name = "przycisk";
przycisk.Dock = DockStyle.Bottom;
przycisk.Text = "Wybierz";
// Assign to our kombo instance
kombo = new ComboBox();
kombo.Name = "kombo";
kombo.Dock = DockStyle.Bottom;
kombo.Items.Add("Przycisk");
kombo.Items.Add("Etykeita");
kombo.Items.Add("Pole tekstowe");
Controls.Add(kombo);
Controls.Add(przycisk);
przycisk.Click += new EventHandler(przycisk_Click);
}
private void przycisk_Click(object sender, EventArgs e)
{
// Using the kombo we created in form load, which is still referenced
// in the class
kombo.Items.Add("Panel"); //just an example
}
You will have to use the FindControl() method to find the object first.
private void przycisk_Click(object sender, EventArgs e)
{
ComboBox kombo = (ComboBox)FindControl("kombo");
kombo.Items.Add("Panel");
}
精彩评论