开发者

Using a control created on Form_Load in another event

开发者 https://www.devze.com 2023-03-04 18:38 出处:网络
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.

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");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号