简体   繁体   English

从另一种形式调用组合框

[英]Calling a combobox from another form

I have a combobox on form1 that I need to call on form2 to get the user selection. 我在form1上有一个组合框,我需要在form2上调用以获得用户选择。 Can some one please give me an example on how to do this? 有人可以给我一个如何做到这一点的例子吗?

EDIT: Forgot to explain what Im trying to do. 编辑:忘了解释我想做什么。 I have a readonly textbox....a user clicks edit to edit the text but I want the text they want/chose to edit to pop up right when form2 is called. 我有一个只读文本框....用户点击编辑来编辑文本,但我希望他们想要/选择编辑的文本在调用form2时弹出。

I have this code on form1 我在form1上有这个代码

    public string SelectedComboValue
    {
        get { return comboBox1.SelectedItem.ToString(); }
    }

And this code on form 2 这个代码在表2中

    EDIT: Added Form1 form1 = null; BUT its still not returning the SelectedComboValue
    public Form2(Form1 parentForm1) : this()
    {
         form1 = parentForm1;
    }

But it gave me an error saying that form1 is not in this context 但它给了我一个错误,说form1不在这种情况下

I suppose that Form1 is the parent of Form2, so when you create the Form2 you use code like this 我认为Form1是Form2的父级,因此当您创建Form2时,您使用这样的代码

Form2 f = new Form2(this);

then in the Form2 class you should have a declaration like this 然后在Form2类中你应该有这样的声明

Form1 _parentForm = null;

and in the Form2 constructor 并在Form2构造函数中

public Form2(Form1 parentForm1) 
{          
    _parentForm = parentForm1;     
} 

If this is true then you can call 如果这是真的那么你可以打电话

_parentForm.SelectedComboValue ;

to get the result required 得到所需的结果

in c# Form 2: create a combobox here 在c#表2中:在这里创建一个组合框

public string strDecVal{
 set{ combobox1.text = value; }
}

in Form 1: for example you have a textbox and a button that will go to form2 在表单1中:例如,您有一个文本框和一个将转到form2的按钮

put these code on your button 把这些代码放在你的按钮上

Form2 frmShow = new Form2(); //Calling the form2
frmShow.strDecVal = textbox1.text;
frmShow.ShowDialog;

In VB it is much more automated: 在VB中,它更加自动化:

Form1: textbox and button in clicking the button in form1 put the code: Form1:单击form1中的按钮的文本框和按钮放置代码:

Form2.Show()

in Form2: on the Load put this code: 在Form2中:在Load上放入此代码:

ComboBox1.Text = Form1.TextBox1.Text

You can wrap the combobox an object of the ComboBox class like this: 您可以将组合框包装为ComboBox类的对象,如下所示:

internal static ComboBox CB=comboBox1;

Then you can call it in the other form, and access all of the methods and attributes of the ComboBox class. 然后,您可以以其他形式调用它,并访问ComboBox类的所有方法和属性。 If you want to add items to that CB, you can do it easily as you do in the parent form. 如果要向该CB添加项目,可以像在父表单中一样轻松完成。 It doesn't matter if it's internal or static, it's just for the example. 它无论是内部的还是静态的,都只是为了这个例子。

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

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