简体   繁体   English

C#WinForms以新形式选择ComboBox项

[英]C# WinForms Selecting ComboBox item in new form

I need a little help. 我需要一点帮助。 I have a main form named Form1 . 我有一个名为Form1的主窗体。 When I click the button btn1 , a new form named Form2 appears. 当我单击按钮btn1 ,将出现一个名为Form2的新表单。 In the Form2 , I have a couple of TextBoxes and a ComboBox named cb2 . Form2 ,我有几个TextBoxes和一个名为cb2的ComboBox。

For the TextBoxes, I set the displayed text in this way: 对于TextBox,我以这种方式设置显示的文本:

//on Form1 I have this code
private void btn1_Click(object sender, EventArgs e)
{
    Form2 form2= new Form2();
    string a = "Text to be displayed in a textBox";
    form2.txtMyTextBox = a;

    form2.Owner = this;
    form2.ShowDialog(this);
}

//on Form2 I set Public String
public string txtMyTextBox
{
    get { return txt1.Text; }
    set { txt1.Text = value; }
}

How do I set the selected item in my ComboBox drop down menu? 如何在ComboBox下拉菜单中设置所选项目? I tried in the same way used in the TextBoxes, but it does not work. 我尝试使用与TextBoxes相同的方式,但是它不起作用。

//Tried for combobox 
public string myCb2
{
    get { return cb2.Text; }
    set { cb2.SelectedValue = value; }
}

You can expose the SelectedIndex property of the ComboBox in a property of the form: 您可以采用以下形式的属性公开ComboBox的SelectedIndex属性:

public int MySelectedIndex // user a more appropriate name
{
    get { return cb2.SelectedIndex; }
    set { cb2.SelectedIndex = value; }
}

This gives you only the index. 这仅给您索引。 If you need the text of the selected item, you need to use SelectedItem : 如果需要所选项目的文本,则需要使用SelectedItem

public string MySelectedItem // user a more appropriate name
{
    get { return cb2.SelectedItem.ToString(); }
}

I used the ToString() method because the type of the SelectedItem is object. 我使用ToString()方法,因为SelectedItem的类型是object。 The underlying type could be anything, according to the objects you filled in the Items property of the ComboBox. 根据您在ComboBox的Items属性中填充的对象,基础类型可以是任何类型。 If you put strings inside, you get strings back, and then you can just use a cast: 如果将字符串放入其中,则会返回字符串,然后可以使用强制转换:

public string MySelectedItem // user a more appropriate name
{
    get { return (string)cb2.SelectedItem; }
    set { return cb2.SelectedItem = value; }
}

尝试使用SelectedIndex并将其分配给Items集合中value Index:

set { cb2.SelectedIndex = cb2.Items.IndexOf(value); }

One way to Pass / Set Data to the Form Initially, is to Create a Constructor which set these values to the controls. 最初将数据传递/设置为表单的一种方法是创建一个将这些值设置为控件的构造函数。

public Form2(string initText, object selectedValue) {
    this.txtMyTextBox.Text = initText;
    this.cb2.SelectedValue = selectedValue;
}

another way is to Expose/create Public properties that work on Controls, if the values to send are more.. 如果要发送的值更多,则另一种方法是公开/创建对控件起作用的公共属性。

根据我的理解,更好的方法是在Form2的构造函数中传递值并在From2_Load事件中设置控件的值,对于组合框设置,它是itemouce而不是设置选定值(确保itemsouce包含选定值并且两者具有相同的实例)。

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

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