简体   繁体   中英

C# WinForms Selecting ComboBox item in new form

I need a little help. I have a main form named Form1 . When I click the button btn1 , a new form named Form2 appears. In the Form2 , I have a couple of TextBoxes and a ComboBox named cb2 .

For the TextBoxes, I set the displayed text in this way:

//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? I tried in the same way used in the TextBoxes, but it does not work.

//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:

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 :

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. The underlying type could be anything, according to the objects you filled in the Items property of the ComboBox. 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包含选定值并且两者具有相同的实例)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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