Click here to Skip to main content
15,311,717 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to get the combobox selectedItem of one form(connect)into another form(Form1)

i Was tried:
1)in connect:form
C#
<pre lang="c#">public string machineId
        {
            get
            {
                return comboBox1.SelectedItem.ToString();
            }
            set
            {
                comboBox1.Text = value;
            }}

and in Form1:
C#
<pre lang="c#">Connect c = new Connect();
                String machineid=c.machineId;



but it's giving nullreference exception.


2)
In Connect form

combox-->Public
and in Form1:

C#
Connect c = new Connect();
                String machineid=c.comboBox1.SelectedItem.ToString();</pre></pre>


eventhough it's returning null value
Posted
Comments
Richard MacCutchan 20-Feb-14 7:05am
   
You create a new Connect object but you never put anything into machineid. It's not clear exactly where the null reference occurs. Are you sure the combobox has been created?

The answer is very simple: a ComboBox, when it is created (instantiated), has its 'SelectedItem Property set to Null. You can verify this by putting this in your code, and setting a break-point, and examining the value in the variable after this line of code executes:
C#
object defaultComboBoxSelectedItem = comboBox1.SelectedItem;
So, you have some choices to make: you can set the 'SelectedItem Property of the ComboBox when the Form is created, and before you try and access it, or, you can change the place in your code in the other Form where the value of ComboBox 'SelectedItem is accessed.

With the first choice, you, in essence, supply a default selection in the ComboBox: that may be very appropriate, or not appropriate: depends on the context.

Or, you can test for SelectedItem == null, and only return some string value that will indicate its null, if the value is null.

The choice you make will depend on your Application, and the intended interaction between your two Forms you wish to present.
   
Comments
Karthik_Mahalingam 20-Feb-14 23:21pm
   
5
Check my past answer here,
Call ComboBox from another form in C#[^]

-KR
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900