简体   繁体   English

从另一个类调用时填充组合框

[英]Fill combobox when calling from another class

I'm very new to C# and I have a problem filling a combobox when calling the method from another class. 我是C#的新手,从另一个类调用方法时,在填充组合框时遇到问题。 My source is like this 我的来源就是这样

class 1 1级

private void btn_login_Click(object sender, EventArgs e)
{
    UserControl1 uc1 = new UserControl1();
    uc1.fill_cbb();
}

class 2 2级

public void fill_cbb()
{
    cbb_table.Items.Add("Text1");
    cbb_table.Items.Add("Text2");
    cbb_table.SelectedIndex = 0;
}

When I do it that way the combobox is empty. 当我这样做时,组合框为空。

如果是Asp,请注意事件IsPostBack

Your problem is not calling the method from another class. 您的问题不是从另一个类调用该方法。 I suppose UserControl1 is your custom user control, and that the "class 2" you mentioned is a userControl1. 我假设UserControl1是您的自定义用户控件,而您提到的“类2”是userControl1。

The code would work as it is, but you are calling it on the wrong instance of that control. 该代码将按原样工作,但是您在该控件的错误实例上调用它。

In your btn_login_Click method, you are generating a totally new instance of UserControl1. 在btn_login_Click方法中,您正在生成UserControl1的全新实例。 You are of course allowed to do that, which is why Visual Studio would never mark it as an error, but uc1 will not be the control that actually sits in your form. 您当然可以这样做,这就是为什么Visual Studio永远不会将其标记为错误,但是uc1不会真正位于表单中的控件的原因。

Let's say in your form you have named the control "cbxOptions". 假设您在表单中将控件命名为“ cbxOptions”。 Then in the button click event, you have to write 然后在按钮单击事件中,您必须编写

cbxOptions.fill_cbb(); cbxOptions.fill_cbb();

instead, if that combobox is also of type UserControl1. 相反,如果该组合框也是UserControl1类型。 Then it should work just fine. 然后它应该工作正常。

Warning, car analogy: It's like when you want a new paint job on your car. 警告,类似于汽车:就像您要在汽车上进行新的油漆作业时。 Then you buy a new car of the same model and take that to the paint shop, get it painted, then bring it to the junkyard and get it crushed. 然后,您购买相同型号的新车,并将其带到喷漆店,将其喷漆,然后将其带到垃圾场并压碎。 Your old car will still have the same old color of course. 当然,您的旧车仍将具有相同的旧颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM