0

我对 C# 很陌生,在从另一个类调用方法时填充组合框时遇到问题。我的来源是这样的

1级

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

2 级

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

当我这样做时,组合框是空的。

4

2 回答 2

2

如果是 Asp 请注意事件 IsPostBack

于 2013-01-17T13:16:51.103 回答
0

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.

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. 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.

Let's say in your form you have named the control "cbxOptions". Then in the button click event, you have to write

cbxOptions.fill_cbb();

instead, if that combobox is also of type 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.

于 2013-01-17T13:18:21.103 回答