Reputation: 127
I have 2 windows forms, they both have same comboboxes with same possible selections. I want to pass selection from one combobox to another on button click. I am passing values successfully to textboxes but when it comes to combobox, I cant figure it out.
Here is the code example:
Form 2 definition
private double passTxt;
private string passCB;
public double passTxtValue
{
get { return passTxt; }
set { passTxt = value; }
}
public string passCbValue
{
get { return passCB; }
set { passCB = value; }
}
Form 1 send
private void btnPassValues_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.passTxtValue = variable1Form1;
form2.passCbValue = CBForm1.SelectedText;
form2.Show();
}
Form2 - load (open)
private void form2_Load(object sender, EventArgs e)
{
variable1Form2.Text = passTxt.ToString();
CBForm2.SelectedText = passCB;
}
When I check with debugger, the error is in step 2. Form1 send empty string ("") for form2.passCbValue = CBValueForm1.SelectedText;
When I try to use index or value it require cast but then there is an error that it can't be casted. Can someone tell me what i do wrong?
Upvotes: 1
Views: 2722
Reputation: 1
//Declare a Global string variable in the Form1
public String testValue;
//Assign the value had in the origin comboBox
testValue = cboOriginValue.Text;
//Create an Form2 Object Type and assign the value in the variable testValue
//to either the textbox or combobox components
Form2 form2 = new Form2();
//Make it visible
form2.Visible = true;
form2.cboVehiculo.Text = tipoAutomovil;
form2.txtRecibe.Text = tipoAutomovil;
When you hit a button or whatever these lines of code being executed you'll have the textboxes or comboboxes components populated with the selected value.
Hope it helps
Upvotes: 0
Reputation: 216253
SelectedText represent the current selected text in the TextBox area of a ComboBox with DropDown style (the blue highlighted text). This selection is cleared every time the combobox looses its focus (and when you are in the button click event, the focus is on the button).
The workaround is to pass the SelectedIndex of the combo on form1 (if the two combos are filled with the same items in the same order)
private void btnPassValues_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.passTxtValue = variable1Form1;
form2.passCbIndex = CBValueForm1.SelectedIndex;
form2.Show();
}
In form2 change the property to get an integer instead of a string....
private int passCBIndex;
public int passCbIndex
{
get { return passCBIndex; }
set { passCBIndex = value; }
}
and in your form2 Load event
private void form2_Load(object sender, EventArgs e)
{
....
CBValueForm2.SelectedIndex = passCBIndex;
}
Upvotes: 1
Reputation: 3133
Change it into:
form2.passCbValue = CBValueForm1.SelectedItem.ToString();
Upvotes: 0