user1080533
user1080533

Reputation: 865

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; }
}

Upvotes: 1

Views: 1275

Answers (4)

Gokul E
Gokul E

Reputation: 1386

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

Upvotes: 0

Nakul Chaudhary
Nakul Chaudhary

Reputation: 26174

As per my understanding better way will be pass value in constructor of Form2 and set the values of controls in From2_Load event and for combobox set it's itemsouce than set selected value(ensure that itemsouce contain selected value and both have same intance.)

Upvotes: 0

valex
valex

Reputation: 24144

Try to use SelectedIndex and assign it to Index of the value in the Items Collection:

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

Upvotes: 2

Moha Dehghan
Moha Dehghan

Reputation: 18472

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; }
}

Upvotes: 3

Related Questions